首页 > 解决方案 > 数据字段中每个不同值的计数

问题描述

我正在寻找一个查询,它将返回表中的每个地区值以及给定时间段内每个不同值的计数

我目前正在使用以下查询

Select count(distinct account_type)
From Table_1
Where date between '2019-08-01' and '2019-08-31' and 
account_type = '0' and 
account_type = '1' and 
account_type = '2' and
account_type = '3' and
account_type = '4'

我正在寻找的结果集如下

account_type     Count
0                 123
1                 456                
2                 789
3                 101112
4                 131415

我得到的结果集是

account_type 
0     

标签: sqlcountdistinct

解决方案


您的 WHERE 子句排除了所有元素,因为它们不能同时属于 0 和 1 类型(等)。
此外,通过count(distinct account_type)您获得不同帐户类型的数量;不是每种帐户类型的元素数量。
尝试这个:

SELECT   account_type,
         COUNT(*)
FROM     table_1
WHERE    date BETWEEN '2019-08-01' AND '2019-08-31'
  AND    account_type IN ('0', '1', '2', '3', '4')
GROUP BY account_type
ORDER BY account_type;

如果account_type始终是单个字符(例如 '06' 不存在),您还可以使用:

AND account_type BETWEEN '0' AND '4'

推荐阅读