Select t1.id1 id,
(Select COUNT(*) From tableName t2 Where t1.id1=t2.id2) COUNT(Id_1),
(Select COUNT(*) From tableName t2 Where t1.id1=t2.id3) COUNT(Id_2)
From tableName t1
下面是与例子的替代:
declare @aa table
(
id1 int,
id2 int,
id3 int
)
insert into @aa
Select
1,0,0
Union All Select
2,0,0
Union All Select
3,1,0
Union All Select
4,1,0
Union All Select
5,0,0
Union All Select
6,0,1
Union All Select
7,2,1
Union All Select
8,0,2
Select t1.id1,IsNull(t2.CountId,0) as [Count(Id_2)],IsNull(t3.CountId,0) as [Count(Id_2)] From @aa t1
Left Join
(
Select COUNT(*) CountId,t2.id2 From @aa t2 Group By t2.id2
)t2
On t1.id1=t2.id2
Left Join
(
Select COUNT(*) CountId,t2.id3 From @aa t2 Group By t2.id3
)t3 On t1.id1=t3.id3
你是什么意思'除了它本身? – Lazykiddy 2013-03-07 14:35:18
欢迎来到StackOverflow。请从[FAQ](http://stackoverflow.com/faq)寻求指导。你的问题需要改进。请用[您尝试过的]更新(http://www.whathaveyoutried.com) – Kermit 2013-03-07 14:35:44
请澄清此部分:“其中Id_1和Id_2可能等于Id,但本身或等于0”。它没有任何意义。究竟是什么**计数**来获得你想要的结果? – 2013-03-07 14:36:03