TB16 är nöjd med hjälpen
TB16 182 – Fd. Medlem
Postad: 5 jun 2019 14:48

PostgreSQL - CASE

Uppgift:

You have access to two tables named top_half and bottom_half, as follows:

top_half schema

id
heads
arms
bottom_half schema

id
legs
tails
You must return a table with the format as follows:

output schema

id
heads
legs
arms
tails
species
The IDs on the tables match to make a full monster. For heads, arms, legs and tails you need to draw in the data from each table.

For the species, if the monster has more heads than arms, more tails than legs, or both, it is a 'BEAST' else it is a 'WEIRDO'. This needs to be captured in the species column.

All rows should be returned (10).

Tests require the use of CASE. Order by species.

Källa:

https://www.codewars.com/kata/sql-basics-monsters-using-case/train/sql

Min lösning:

SELECT top_half.*, bottom_half.*,
CASE
WHEN (heads > arms) THEN 'BEAST'
WHEN (tails > legs) THEN 'BEAST'
ELSE 'WEIRDO'
END AS species
FROM top_half, bottom_half
ORDER BY species
LIMIT 10

Felmeddelande (PostgreSQL 9.6):

Fråga:
Är det någon som ser var jag gör fel? Jag förstår inte vad jag gör för fel

joculator 5285 – F.d. Moderator
Postad: 6 jun 2019 09:43

Se på hur du skrivit din join (det är en join även om du inte skrivit ordet 'join'). Om du gör select från flera tabeller vill du oftast (nästan alltid) beskriva dessa tabellers relation.

TB16 182 – Fd. Medlem
Postad: 6 jun 2019 18:58
joculator skrev:

Se på hur du skrivit din join (det är en join även om du inte skrivit ordet 'join'). Om du gör select från flera tabeller vill du oftast (nästan alltid) beskriva dessa tabellers relation.

Beskriver man tabellernas relation med hjälp av join eller bara villkoret top_half.id = bottom_half.id
Jag skrev om min kod och den passerade alla tester (se nedan)

SELECT top_half.id, top_half.heads, bottom_half.legs, top_half.arms, bottom_half.tails,
CASE
WHEN (heads > arms) OR (tails > legs) THEN 'BEAST'
ELSE 'WEIRDO'
END AS species
FROM (top_half join bottom_half on top_half.id = bottom_half.id)
GROUP BY top_half.id
ORDER BY species
LIMIT 10

joculator 5285 – F.d. Moderator
Postad: 7 jun 2019 08:11

Det finns flera olika sätt att skriva joins. Här visar de minst 2:

https://www.postgresql.org/docs/8.3/tutorial-join.html

TB16 182 – Fd. Medlem
Postad: 7 jun 2019 09:33
joculator skrev:

Det finns flera olika sätt att skriva joins. Här visar de minst 2:

https://www.postgresql.org/docs/8.3/tutorial-join.html

Okej, tack för hjälpen

Svara Avbryt
Close