日期:2014-05-17 浏览次数:20611 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-01-16 23:32:12
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:
if object_id('tbname') is not null
drop table [tbname]
go
create table [tbname](mlszh varchar(20),yclsj int)
insert [tbname]
SELECT 1,'23'union all
select 1,'34' union all
select 1,NULL union all
select 1,NULL union all
select 1,0 union all
select 2,34 union all
select 2,NULL union all
select 2,0 union all
select 2,56 union all
select 2,67
--------------开始查询--------------------------
select mlszh,COUNT(mlszh) [总记录数],SUM(CASE WHEN yclsj=0 OR yclsj IS NULL THEN 1 ELSE 0 END) AS [为0或者NULL的行数]
,COUNT(mlszh)-SUM(CASE WHEN yclsj=0 OR yclsj IS NULL THEN 1 ELSE 0 END) AS [部不为0且不为NULL的行数]
from [tbname]
GROUP BY mlszh
----------------结果----------------------------
/*
mlszh 总记录数 为0或者NULL的行数 部不为0且不为NULL的行数
-------------------- ----------- ----------- --------------
1 5 3 2
2 5 2 3
(2 行受影响)
*/