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