Sql条件计数

时间:2017-03-23 16:41:16

标签: sql sqlite

任何人都可以帮我处理以下条件的sql和sqlite查询。具体来说,我想显示两个类别的合并计数。

**Table**
Category    Sub_category
  A              1
  A              2
  A              2
  B              1
  C              1
  C              1
  C              2
  D              1
  D              1
  D              1
  D              2
  D              3
**Required Output**
    Category    Sub_category    Count   **condition(not part of o/p just instruction)**
        A             1           1        -
        A             2+          2        -    
        B             1           1        -    
        C             1           2        -
        C             2+          1        -
        D             1           3        -    
        D             2+          1 should contain the count of 2 and more

我可以使用以下方法实现相同目的:

  select Category,
         count(CASE WHEN Sub_category = 1 THEN Sub_category END) AS '1',
         count(CASE WHEN Sub_category >= 2 THEN Sub_category END) AS '2+'
  from table

然而输出差别不大,因此仅查找第一个输出。

**Output**
Category    1   2+
   A        1   2
   B        1   0
   C        1   2
   D        3   2

提前致谢!

2 个答案:

答案 0 :(得分:3)

你想:

select Category,
       (case when sub_category = 1 then '1' else '2+' end) as sub_category,
       count(*)
from table
group by Category,
         (case when sub_category = 1 then '1' else '2+' end);

也就是说,您希望将子类别组放在上,而不是列。

答案 1 :(得分:1)

您只缺少一列。添加最后一次计数而不进行过滤以获得总计:

select Category,
     count(CASE WHEN Sub_category = 1 THEN Sub_category END) AS '1',
     count(CASE WHEN Sub_category >= 2 THEN Sub_category END) AS '2+',
     count(*)
   from table
   group by Category, count(CASE WHEN Sub_category = 1 THEN Sub_category END), count(CASE WHEN Sub_category >= 2 THEN Sub_category END), count(*)