2013-03-07 45 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 
相关问题