读书人

:使用SQL中的COUNT来统计某个字段中符

发布时间: 2012-04-12 15:46:35 作者: rapoo

求助:使用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 

读书人网 >SQL Server

热点推荐