我的数据就像这样。
+------------+----------------+--------+-------+
| date | shop_id | status | count |
+------------+----------------+--------+-------+
| 2016-04-01 | 121101201 | A | 9 |
| 2016-04-01 | 121101201 | B | 6 |
| 2016-04-04 | 121101201 | A | 4 |
| 2016-04-04 | 121101201 | B | 5 |
| 2016-04-05 | 121101201 | A | 11 |
| 2016-04-05 | 121101201 | B | 3 |
我想进行查询并像这样返回。
+------------+----------------+----------+----------+
| date | shop_id | status=A | status=B |
+------------+----------------+----------+----------+
| 2016-04-01 | 121101201 | 9 | 6 |
| 2016-04-04 | 121101201 | 4 | 5 |
| 2016-04-05 | 121101201 | 11 | 3 |
如何为上述输出进行sql查询。
感谢您的帮助和分享。
答案 0 :(得分:1)
SELECT date,
shop_id,
SUM(case when status='A' then count else 0 end) AS `status=A`,
SUM(case when status='B' then count else 0 end) AS `status=B`
FROM table_name
GROUP BY date, shop_id
ORDER BY date desc
答案 1 :(得分:0)
您可以使用条件聚合执行此操作:
SELECT `date`, shop_id,
SUM(status='A') AS `status=A`,
SUM(status='B') AS `status=B`
FROM mytable
GROUP BY `date`, shop_id