2013-03-07 53 views
0

我有一個MySQL表是這樣的:MySQL的數列中的值等於另一列

Id Id_1 Id_2 
1  0 0 
2  0 0 
3  1 0 
4  1 0 
5  0 0 
6  0 1 
7  2 1 
8  0 2 

其中ID_1和ID_2可以等於標識除了本身或等於0

,我想通過使用最有效的查詢來獲得此結果:

id COUNT(Id_1) COUNT(Id_2) 
1   2    2 
2   1    1 
3   0    0 
4   0    0 
5   0    0 
6   0    0 
7   0    0 
8   0    0 

謝謝!

+0

你是什麼意思'除了它本身? – Lazykiddy 2013-03-07 14:35:18

+0

歡迎來到StackOverflow。請從[FAQ](http://stackoverflow.com/faq)尋求指導。你的問題需要改進。請用[您嘗試過的]更新(http://www.whathaveyoutried.com) – Kermit 2013-03-07 14:35:44

+0

請澄清此部分:「其中Id_1和Id_2可能等於Id,但本身或等於0」。它沒有任何意義。究竟是什麼**計數**來獲得你想要的結果? – 2013-03-07 14:36:03

回答

0

你的解釋不是很清楚,但根據您的樣本數據和期望的輸出,你可以用兩個子查詢外做到這一點加入到基表,就像這樣:

select a.id, 
    coalesce(b.id_1_count,0), 
    coalesce(c.id_2_count,0) 
from so15273831 a 
left outer join (
    select id_1, count(*) as id_1_count 
    from so15273831 
    group by id_1 
) b on b.id_1 = a.id 
left outer join (
    select id_2, count(*) as id_2_count 
    from so15273831 
    group by id_2 
) c on c.id_2 = a.id 
order by a.id; 

SQL小提琴這裏:http://sqlfiddle.com/#!2/71b67/1

0

您可以使用CASE語句,子查詢以獲得您想要的結果

SELECT ID, SUM(id1.ids), SUM(id2.ids) 
FROM mytable 
LEFT OUTER JOIN 
    (SELECT id_1, count(id) ids 
    FROM my table 
    GROUP BY id_1) AS id1 ON mytable.ID = id1.id_1 
LEFT OUTER JOIN 
    (SELECT id_2, count(id) ids 
    FROM my table 
    GROUP BY id_2) AS id2 AS id2 ON mytable.ID = id2.id_2 
GROUP BY ID 
ORDER BY ID 
0
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 
相關問題