SQL命令按日期汇总数据组

时间:2016-10-10 16:28:40

标签: sql

我有一个包含以下内容的数据库:

+----+---------------------+-------------+-----------------+
| id | date                |          pay|        usr_type |
+----+---------------------+-------------+-----------------+
|  1 | 2016-10-17          |          500|             boss|
|  2 | 2016-10-17          |          200|             boss|
|  3 | 2016-10-24          |          300|             user|
|  4 | 2016-10-24          |          100|             user|
+----+---------------------+-------------+-----------------+

我希望结果如下:

+---------------------+-------------+-----------------+
| date                |         user|             boss|
+----+---------------------+--------+-----------------+
| 2016-10-17          |            0|              700|
| 2016-10-24          |          400|                0|
+----+---------------------+-------------+------------+

1 个答案:

答案 0 :(得分:1)

以下是使用conditional aggregation的一个选项:

select date, 
    sum(case when usr_type = 'user' then pay else 0 end) user,
    sum(case when usr_type = 'boss' then pay else 0 end) boss
from yourtable
group by date