我必须使用SQL子查询来回答以下问题。
原始表是 奖
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第一个第二个第三个 101 120 60 30 .....
我的回答是: 使用horsedb;
SELECT event_id,
(SELECT money FROM prize WHERE place = '1' AND event_id = prize.event_id) AS 'First',
(SELECT money FROM prize WHERE place = '2' AND event_id = prize.event_id) AS 'Second',
(SELECT money FROM prize WHERE place = '3' AND event_id = prize.event_id) AS 'Third'
FROM prize
ORDER BY event_id;
但答案有1024(返回多行)错误。我试过IN,任何结果都不好 请帮助,谢谢
答案 0 :(得分:0)
以下是查询:
select event_id,
max(first) as first,
max(second) as second,
max(third) as third
from (select event_id,
case when place = 1 then money else null end as first,
case when place = 2 then money else null end as second,
case when place = 3 then money else null end as third
from prize
)t
group by event_id;
如果你需要它可以使用sqlfiddle: http://sqlfiddle.com/#!2/aa691/1/0
答案 1 :(得分:0)
关于输出应该是什么样的问题不明确,但这里有一个建议: 尝试使用GROUP BY和GROUP_CONCAT。例如:
SELECT event_id,
GROUP_CONCAT(place ORDER BY place) AS place,
GROUP_CONCAT(money ORDER BY place) AS money
FROM prize
GROUP BY event_id;
给出:
+----------+-----------+---------------------+
| event_id | place | money |
+----------+-----------+---------------------+
| 101 | 1,2,3 | 120,60,30 |
| 102 | 1,2,3 | 10,5,2 |
| 103 | 1,2,3 | 100,60,40 |
| 401 | 1,2,3,4,5 | 1000,500,250,100,50 |
+----------+-----------+---------------------+