现有表如下:
id type
111 W
111 T
111 W
222 U
111 W
我想得到的结果集如下:
id CountW CountT CountU
111 2 1 0
222 0 0 1
就是要根据id和type,同时就行分组,并计算出W,T,U各自出现的数量,形成结果集。
请教如何实现?(不要用游标)谢谢!!
------解决方案--------------------
你的结果不对吧
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-07-11 08:23:15
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[type] varchar(1))
insert [tb]
select 111,'W' union all
select 111,'T' union all
select 111,'W' union all
select 222,'U' union all
select 111,'W'
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename('Count'+[type])+'=count(case when [type]='+quotename([type],'''')+' then 1 else null end)'
from tb group by [type]
exec('select [id]'+@s+' from [tb] group by [id]')
----------------结果----------------------------
/*
id CountT CountU CountW
----------- ----------- ----------- -----------
111 1 0 3
222 0 1 0
*/
------解决方案--------------------
如果你的type是固定的,直接写死,我这是动态的,写死就是:
SELECT [id] ,
[CountT] = COUNT(CASE WHEN [type] = 'T' THEN 1
ELSE NULL
END) ,
[CountU] = COUNT(CASE WHEN [type] = 'U' THEN 1
ELSE NULL
END) ,
[CountW] = COUNT(CASE WHEN [type] = 'W' THEN 1
ELSE NULL
END)
FROM [tb]
GROUP BY [id]