问题
I have a database of race results. Each race event has multiple classes.
events
table:
event_id | event_date
---------+------------
1 | 11/5/14
2 | 11/12/14
3 | 11/19/14
results table:
result_event | name | class | position
-------------+---------------+-------+-----------
1 | Jason Smith | 40 | 1
1 | David Johnson | 40 | 2
1 | Randy White | 30 | 1
1 | Billy Hansen | 30 | 2
2 | Wally Mann | 40 | 1
2 | Shawn Little | 40 | 2
2 | Eric Davis | 30 | 1
2 | Tom Handy | 30 | 2
I want to create a summary table that lists the Event Date and the winners of each class.
Like this:
Event Date | Class 40 Winner | Class 30 Winner
------------+-----------------+------------------
11/5/14 | Jason Smith | Randy White
11/12/14 | Wally Mann | Eric Davis
What query would I need so that I can create a GROUP BY event_id
and list winners in separate columns?
回答1:
You can join the events
table on two queries from the results
table, one for each class:
SELECT event_data, class_40_winner, class_30_winner
FROM events e
LEFT JOIN (SELECT result_event, name AS class_40_winner
FROM results
WHERE class = 40 AND position = 1) c40 ON e.id = c40.result_event
LEFT JOIN (SELECT result_event, name AS class_30_winner
FROM results
WHERE class = 30 AND position = 1) c30 ON e.id = c30.result_event
回答2:
You are querying like pivoting data, so I suggest you to use a query like this:
select event_date
, max(case when r.class = 40 then name end) `Class 40 Winner`
, max(case when r.class = 30 then name end) `Class 30 Winner`
from events e
left join results r on e.event_id = r.result_event and r.position = 1
group by event_date;
[SQL Fiddle Demo]
来源:https://stackoverflow.com/questions/31012881/sql-group-by-using-strings-in-new-columns