SQL-在单个记录中分组和汇总

时间:2019-02-13 15:14:15

标签: sql

我有一个表,其中包含如下所示的订单行。

| product_id |  amount |  shop_id |
|------------|---------|----------|
|       1234 |       1 |  a       |
|       1234 |       2 |  b       |
|       1234 |       3 |  c       |
|       1234 |       2 |  a       |
|       1234 |       2 |  b       |
|       2222 |       1 |  a       |
|       2222 |       4 |  b       |

我要查找的结果是一条记录,该记录将“总金额”列中的总金额加起来,并在各列中加上每个shop_id的“总金额” 因此,根据以上数据,结果应如下所示:

| product_id |  amount total |  amount shop_id a |  amount shop_id b |  amount shop_id c |
|------------|---------------|-------------------|-------------------|-------------------|
|       1234 |            10 |                 3 |                 4 |                 3 |
|       2222 |             5 |                 1 |                 4 |                 0 |

这有可能实现吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

您需要条件聚合:

SELECT product_id,
       SUM(amount) as amount_total,
       SUM(CASE WHEN shop_id = 'a' THEN amount ELSE 0 END) as amount_shop_id_a,
       SUM(CASE WHEN shop_id = 'b' THEN amount ELSE 0 END) as amount_shop_id_b,
       SUM(CASE WHEN shop_id = 'c' THEN amount ELSE 0 END) as amount_shop_id_c
FROM table t
GROUP BY product_id;