在SQL中编写和执行子查询

时间:2019-07-04 12:47:29

标签: mysql

我有这张桌子:

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

4 个答案:

答案 0 :(得分:2)

假设位置等于第一,第二,第三等,那么相关的子查询可能就是您要寻找的

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。

答案 1 :(得分:1)

假设您只希望第一个,第二个和第三个具有以下结果:

Event_id|First|Second|Third|
--------|-----|------|-----|
     101|  120|    60|   30|
     102|   10|     5|    2|
     103|  100|    60|   40|
     401| 1000|   500|  250|

您可以跳过子查询并使用ifsum。 这是您的目标:

SELECT Event_id
, SUM(if (place = 1, money, null)) AS `First`
, SUM(if (place = 2, money, null)) AS `Second`
, SUM(if (place = 3, money, null)) AS `Third`
FROM prize
GROUP by Event_id

现在稍微解释一下。对于每一行,您提取money是否应位于第一,第二或第三列中。提取这些值后,可以按Event_id分组并汇总所有值。

如果需要更多值,则只需添加额外的列。

答案 2 :(得分:0)

如果您固定了3列,请使用

select prize2.event_id,
 (select money from prize where event_id= prize2.event_id order by place limit 0,1) as First, 
 (select money from prize where event_id= prize2.event_id order by place limit 1,1) as Second, 
 (select money from prize where event_id= prize2.event_id order by place limit 2,1) as Third
from prize AS prize2
group by event_id;

DEMO

答案 3 :(得分:0)

尝试一下,可能有帮助

SELECT Event_id,
    SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(money), ',',1), ',', -1) AS First, 
    SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(money), ',',2), ',', -1) AS Second,
    SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(money), ',',3), ',', -1) AS Third
FROM `prize` WHERE place in (1,2,3) GROUP BY Event_id order By Event_id ASC