日期:2014-05-18  浏览次数:20467 次

求助:使用SQL中的COUNT来统计某个字段中符合条件的列数
我的数据库表中有字段“State”(范围为1到4的int类型的数据),现在我需要使用COUNT语句(不用SUM函数)来分别统计State=1的列数,State=2的列数,State=3的列数,State=4的列数等,请问该如何编写SQL语句。

------解决方案--------------------
SQL code
--1
select 
(select count(1) from tb where State = 1) [1],
(select count(1) from tb where State = 2) [2],
(select count(1) from tb where State = 3) [3],
(select count(1) from tb where State = 4) [4]


--2
select 
  sum(case State when 1 then 1 else 0 end) [1],
  sum(case State when 2 then 1 else 0 end) [2],
  sum(case State when 3 then 1 else 0 end) [3],
  sum(case State when 4 then 1 else 0 end) [4]
from tb

------解决方案--------------------
SQL code

select distinct state,count(1) over (partition by state) from tab