SQL Group BY在新列中使用字符串

时间:2015-06-23 20:28:49

标签: mysql sql select group-by

我有一个比赛结果数据库。每个比赛活动都有多个班级。

event_id | event_date ---------+------------ 1 | 11/5/14 2 | 11/12/14 3 | 11/19/14 表:

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

结果表:

Event Date  | Class 40 Winner | Class 30 Winner
------------+-----------------+------------------
11/5/14     | Jason Smith     | Randy White
11/12/14    | Wally Mann      | Eric Davis

我想创建一个汇总表,列出事件日期和每个班级的获胜者。

像这样:

GROUP BY event_id

我需要什么查询才能在单独的列中创建select ti.id_totalingresos from TotalIngresos ti, ParcialTotal pt, IngresosParciales ip where ti.id_totalingresos = pt.idtotales_FK and pt.idparciales_FK = ip.id_ingresosparciales and ip.periodo = 6 group by ti.id_totalingresos having SUM(ip.monto) = 5249866 和列表获胜者?

2 个答案:

答案 0 :(得分:1)

您可以在events表的两个查询中加入results表,每个类一个:

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

答案 1 :(得分:0)

您正在查询数据透视,因此我建议您使用如下查询:

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]