[code=sql]USE tempdb
IF OBJECT_ID('TEST') IS NOT NULL
DROP TABLE TEST; --> 如果表TEST不为空,删除表
GO
CREATE TABLE TEST --> 创建表,字段及类型如下
(
id int,
type nvarchar(10)
);
GO
INSERT INTO TEST VALUES --> 向表中插入数据
(1001,'a'),
(1001,'a'),
(1004,'b'),
(1001,'b'),
(1005,'c'),
(1004,'a'),
(1001,'c');
GO
--------------------开始查询--------------------
;with a as
(
select id,COUNT(1)as total
from Test
group by id
),
b as
(
select id,type,COUNT(1) as cou
from Test
group by id,type
),
c as
(
select id,a,b,c
from b
pivot(max(cou) for type in (a,b,c))as t
)
select a.id,a.total,c.a,c.b,c.c
from a
join c
on a.id = c.id
--------------------运行结果--------------------
/*
id total a b c
----------- ----------- ----------- ----------- -----------
1001 4 2 1 1
1004 2 1 1 NULL
1005 1 NULL NULL 1
(3 行受影响)
*/[/code] |