TB16 behöver inte mer hjälp
TB16 182 – Fd. Medlem
Postad: 5 jun 2019 16:40

PostgreSQL - Simple table totaling

Uppgift:

For this challenge you need to create a simple query to display each unique clan with their total points and ranked by their total points.

people table schema

  • name
  • points
  • clan

You should then return a table that resembles below

select on

  • rank
  • clan
  • total_points
  • total_people
    The query must rank each clan by their total_points, you must return each unqiue clan and if there is no clan name you must replace it with [no clan specified], you must sum the total_points for each clan and the total_people within that clan.

    Källa: https://www.codewars.com/kata/sql-basics-simple-table-totaling/train/sql


Min lösning (PostgreSQL 9.6):

select sum(points) as rank, clan, sum(points) as total_points, count(name) as total_people,
CASE
WHEN clan = null THEN '[no clan specified]'
END AS clan
from people
group by clan
order by total_points desc

Output:

Fråga:
Av någon anledning så verkar de tomma rutorna inte ersättas med texten 'no clan specified' i clan-kolumnen. Jag har även testat funktionen coalesce för att skriva in text i de rutor som innehåller null på följande vis:
COALESCE(people.clan,'No clan specified') AS clan

Kan någon se varför? Dessutom bör väl varje rad innehålla en unik klan, men det gör den inte enligt utskriften. Har suttit i flera timmar utan att komma vidare :S


Får följande felmeddelande:
"Test Failedexpected: >= 1401217
got: 225514"

TB16 182 – Fd. Medlem
Postad: 8 jun 2019 12:51

Löste den på följande vis:

SELECT RANK() OVER (ORDER BY SUM(points) DESC), COALESCE(NULLIF(clan,''), '[no clan specified]') AS clan, SUM(points) AS total_points, COUNT(*) AS total_people FROM people GROUP BY clan ORDER BY total_points DESC

Svara
Close