当前位置: 代码迷 >> Sql Server >> :使用SQL中的COUNT来统计某个字段中符合条件的列数
  详细解决方案

:使用SQL中的COUNT来统计某个字段中符合条件的列数

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

------解决方案--------------------
SQL code
--1select (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]--2select   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
  相关解决方案