我有一个像这样的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可以等于Id,除了它本身或等于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 :(得分:0)
您可以使用带有subQueries的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
答案 1 :(得分: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;
答案 2 :(得分: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