我有这张表:
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
我正在尝试编写和执行 SQL 子查询。到目前为止,我已经想到了这个,但我似乎无法完成它以获得我想要的结果。
select event_id,
(select money from prize where ) as First,
(select money from prize where ) as Second,
(select money from prize where ) as Third
from prize AS prize2
group by event_id;
这是我的预期结果:
Event_id First Second Third
101 120 60 30
最佳答案
假设地点等于第一、第二、第三等,那么相关的子查询可能就是您要查找的内容
select event_id,
(select money from t t1 where place = 1 and t1.event_id = t.event_id ) as First,
(select money from t t1 where place = 2 and t1.event_id = t.event_id ) as Second,
(select money from t t1 where place = 3 and t1.event_id = t.event_id ) as Third
from t
group by event_id;
+----------+-------+--------+-------+
| event_id | First | Second | Third |
+----------+-------+--------+-------+
| 101 | 120 | 60 | 30 |
| 102 | 10 | 5 | 2 |
| 103 | 100 | 60 | 40 |
| 401 | 1000 | 500 | 250 |
+----------+-------+--------+-------+
4 rows in set (0.00 sec)
但这是对 group by 的无效使用,因为没有进行聚合。并且您需要应用 where 子句以限制为 even_id 101。
关于mysql - 在 SQL 中编写和执行子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56888304/