单组功能 - 按类别和区域计算的产品数量

时间:2017-07-27 07:25:18

标签: sql group-by

我在线查看,无法找到以下问题的答案。

我想创建下表。我可以创建除Count_product_Acount_product_B之外的所有列。

链接到表格:

Link to table

链接到table1:

Linke to table 1

Select 
  Region_flag, type, count(total product)
  ,sum(Case when product in ('A') then count(total product) END) as count_product_A
  ,sum(Case when product in ('B') then count(total product) END) as count_product_B
FROM Table1 
Group by
  Region_flag, type

1 个答案:

答案 0 :(得分:2)

尝试此查询:

SELECT 
  region_flag, type,
  count(1) AS count_total,
  sum(CASE WHEN product IN ('A') THEN 1 ELSE 0 END) AS count_product_A,
  sum(CASE WHEN product IN ('B') THEN 1 ELSE 0 END) AS count_product_B
FROM
  table1 
GROUP BY
  region_flag, type