日期:2014-05-16 浏览次数:20730 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-13 10:22:07
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([id] int,[pid] int,[aname] varchar(4))
insert [a]
select 1,0,'张三' union all
select 2,1,'李四' union all
select 3,0,'王五' union all
select 4,2,'李六'
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go
create table [b]([id] int,[aid] int,[bname] varchar(6),[bstatus] int)
insert [b]
select 1,2,'数据一',0 union ALL
select 2,1,'数据二',0 union all
select 3,2,'数据三',0
--------------开始查询--------------------------
;WITH cte AS
(select aname,COUNT( b.id )[count],a.pid,a.id
FROM a LEFT JOIN [b] ON b.aid= a.id
GROUP BY aname ,a.pid,a.id)
SELECT a.aname,a.[count] [一级],ISNULL(b.[count],0)[二级]
FROM cte a LEFT JOIN cte b ON a.id=b.pid
----------------结果----------------------------
/*
aname 一级 二级
----- ----------- -----------
李六 0 0
李四 2 0
王五 0 0
张三 1 2
*/