我有一个像这样的MySQL:
+----+----------+---------+---------------------+
| id | event | seconds | date |
+----+----------+---------+---------------------+
| 5 | open | 0 | 2014-10-20 16:00:00 |
| 5 | assign | 5 | 2014-10-20 16:00:05 |
| 5 | complete | 10 | 2014-10-20 16:00:15 |
| 5 | close | 22 | 2014-10-20 16:00:37 |
| 6 | open | 0 | 2014-10-20 17:00:00 |
| 6 | assign | 7 | 2014-10-20 17:00:07 |
+----+----------+---------+---------------------+
是否有一个select语句可以在不编写程序逻辑的情况下返回它?
+----+----------+---------+-----------+---------+
| id | open | assign | complete | close |
+----+----------+---------+-----------+---------+
| 5 | 0 | 5 | 10 | 22 |
| 6 | 0 | 7 | | |
+----+----------+---------+-----------+---------+
答案 0 :(得分:2)
SELECT id,
SUM(CASE WHEN event='open' THEN seconds ELSE 0 END) as open,
SUM(CASE WHEN event='assign' THEN seconds ELSE 0 END) as assign,
SUM(CASE WHEN event='complete' THEN seconds ELSE 0 END) as complete,
SUM(CASE WHEN event='close' THEN seconds ELSE 0 END) as close
FROM t
GROUP BY id
我假设你需要每个id的秒数,它可以是max,min等。
答案 1 :(得分:2)
这是将行转换为列,我们可以进行基于CASE的聚合
SELECT id,
MAX( case when event ='open' then seconds end ) as open,
MAX( case when event ='assign' then seconds end ) as assign,
MAX( case when event ='complete' then seconds end ) as complete,
MAX( case when event ='close' then seconds end ) as close
FROM Table1
GROUP BY id