所以我有一个看起来像这样的表:(称为PRIZE)
Event_id Place Money
101 1 120
101 2 60
101 3 30
102 1 10
102 2 5
102 3 2
103 1 100
103 2 60
103 3 40
401 1 1000
401 2 500
401 3 250
401 4 100
401 5 50
我试图回答这个问题: '对于每个活动,在一行上列出可用于第一,第二和第三名的奖金。按event_id分组。
例如。将出现一行结果:
Event_id First Second Third
101 120 60 30
到目前为止我已经知道了这一点:
SELECT Event_id, Money AS 'First'
FROM PRIZE
WHERE Place = '1'
GROUP BY Event_id;
但我真的无法在第二个'中添加SQL。和'第三'部分问题。
有人可以帮忙吗?
谢谢!
答案 0 :(得分:1)
为什么不使用多个连接执行一个select语句,而不是使用子查询执行多个选择?
SELECT tb.event_id,
tb1.money AS first,
tb2.money AS second,
tb3.money AS third
FROM prize tb
INNER JOIN prize tb1 ON tb1.event_id = tb.event_id AND tb1.place = 1
INNER JOIN prize tb2 ON tb2.event_id = tb.event_id AND tb2.place = 2
INNER JOIN prize tb3 ON tb3.event_id = tb.event_id AND tb3.place = 3
GROUP BY tb.event_id;
答案 1 :(得分:1)
我会使用条件聚合来解决这个问题:
/my/logdir/Host1Server1.log
/my/logdir/Host1Server2.log
/my/logdir/Host2Server1.log
/my/logdir/Host2Server2.log
注意:如果有关系,那么这会增加所有地方的钱。
答案 2 :(得分:0)
SELECT E.Event_ID,
(SELECT Money FROM PRIZE AS p1 WHERE Place = '1' AND p1.Event_ID = e.Event_ID) AS 'First',
(SELECT Money FROM PRIZE AS p2 WHERE Place = '2' AND p2.Event_ID = e.Event_ID) AS 'Second',
(SELECT Money FROM PRIZE AS p3 WHERE Place = '3' AND p3.Event_ID = e.Event_ID) AS 'Third'
FROM
(SELECT DISTINCT Event_ID
FROM PRIZE) AS E
希望这有帮助
答案 3 :(得分:0)
如果每个地方只有一个价格,并且每个Event_id这个查询应该适合您的目的。
Select Event_id
,FIRST=Max(CASE WHEN Place=1 THEN Money END)
,SECOND=Max(CASE WHEN Place=2 THEN Money END)
,THIRD=Max(CASE WHEN Place=3 THEN Money END)
from PRIZE
Group by Event_id
答案 4 :(得分:0)
如果您只想要三列,那么使用条件聚合是最简单的数据透视方式:
select
event_id
, max(case when place=1 then money end) as first
, max(case when place=2 then money end) as second
, max(case when place=3 then money end) as third
from
prize
group by
event_id;
如果你想要一个动态解决方案,每个地方都有一个列,那么这个查询(改编自this question and answer)会这样做:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN Place = ''',
Place,
''' THEN Money END) AS `',
Place, '`'
)
) INTO @sql
FROM prize;
SET @sql = CONCAT('SELECT Event_id, ', @sql, '
FROM prize
GROUP BY Event_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这会将数字作为列名,但是如果你想要序数,你可以创建一个查找表并加入它。
Sample SQL Fiddle两种解决方案。