问题如下:对于每个活动,在一行上列出可获得一等奖,二等奖和三等奖的奖金。
所以我需要列出PRIZE表中的EVENT_ID。然后将有三个单独的列显示第一,第二和第三奖。
预期数据如下:
| event_id | First | Second | Third |
| 101 | 120 | 60 | 30 |
| 102 | 10 | 5 | 2 |
| 103 | 100 | 60 | 40 |
| 401 | 1000 | 500 | 250 |
表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 |
到目前为止,我有:
SELECT event_id, money AS First, money AS Second, money AS Third
FROM PRIZE
WHERE money IN
(SELECT money FROM PRIZE WHERE place=1 IN
(SELECT money FROM PRIZE WHERE place=2 IN
(SELECT money FROM PRIZE WHERE place=3
GROUP BY event_id)));
SQL只提供一个'OK'语句,并且不显示表。请帮忙吗?
答案 0 :(得分:2)
我认为最简单的方法是使用substring_index()
和group_concat()
将它们全部放在一列中:
select event_id,
substring_index(group_concat(money order by place), ',', 3)
from prize
group by event_id;
或者,对于三个单独的列,条件聚合也非常简单:
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;
答案 1 :(得分:0)
我的建议:
SELECT event_id,
(SELECT Money FROM prize WHERE event_id=p.event_id AND place=1) AS First,
(SELECT Money FROM prize WHERE event_id=p.event_id AND place=2) AS Second,
(SELECT Money FROM prize WHERE event_id=p.event_id AND place=3) AS Third,
FROM prize p
评论后编辑:添加:
GROUP BY event_id