我的目标是实现如下结果集
CODE | TOTAL1 | TOTAL2
1 | 56 | 34
2 | 12 | 15
3 | 90 | 3
有2个表,例如tableA和tableB
tableB.type
SELECT code, COUNT (*) AS total1
FROM tableA a
WHERE a.ID IN (select ID from tableB
where type = 'XYZ')
GROUP BY code
SELECT code, COUNT (*) AS total2
FROM tableA a
WHERE a.ID IN (select ID from tableB
where type = 'ABC')
GROUP BY code
我想在同一个查询中显示每种类型的每个代码的计数
提前致谢
答案 0 :(得分:3)
没有子查询
SELECT a.code,
sum(decode(b.type,'ABC',1,0)) AS total1,sum(decode(b.type,'XYZ',1,0)) AS total2
FROM tableA a
join tableB b on a.ID = b.ID
GROUP BY a.code
问候
ķ
答案 1 :(得分:1)
子查询:
SELECT code, (select COUNT (*) AS total1
FROM tableA a1
WHERE a.ID IN (select ID from tableB
where type = 'XYZ')
and a1.code = tableA.code) as Total1,
(select COUNT (*) AS total2
FROM tableA a2
WHERE a.ID IN (select ID from tableB
where type = 'ABC')
and a2.code = tableA.code) as Total2)
from tableA
group by Code
答案 2 :(得分:1)
可能其中许多方法之一是在内联视图中将两者联合起来,然后选择计数总和,如下所示:
SELECT代码,SUM(total1)total1,SUM(total2)total2 FROM
(
SELECT代码,COUNT()total1,0 total2
来自tableA a
在哪里a.ID IN(从tableB中选择ID
其中type ='XYZ')
GROUP BY代码
联盟
SELECT代码,0,COUNT()
来自tableA a
在哪里a.ID IN(从tableB中选择ID
其中type ='ABC')
GROUP BY代码
)
GROUP BY代码;