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