假设我有两个表GOOD
和BAD
来存储小部件生成的记录。我的表看起来像这样
Widget Good
----------------
Widget A Y
Widget A Y
Widget B Y
Widget Bad
----------------
Widget A Y
Widget B Y
我有这两个基本查询
select count(*) as good from table_good where widget = 'Widget A' and Good = 'Y'
select count(*) as bad from table_bad where widget = 'Widget A' and Bad = 'Y'
这会产生两个这样的表
good
----
2
bad
---
1
我想将这些组合成一个单独的查询,在那里我会找回一个包含单个记录的表
good bad
-----------
2 1
有人能指出我该怎么做。我认为做一个联合并在其他表中设置假列会选择这样做,但我得到了正确的表模式,但有两个单独的记录。
谢谢!
答案 0 :(得分:5)
试试这个:
SELECT (SELECT COUNT(*) AS good
FROM table_good
WHERE widget = 'Widget A'
AND good = 'Y') AS good,
(SELECT COUNT(*) AS bad
FROM table_bad
WHERE widget = 'Widget A'
AND bad = 'Y') AS bad
FROM dual
答案 1 :(得分:1)
另一种方法是使用FULL JOIN
:
SELECT COALESCE(A.widget,B.widget) AS Widget, COUNT(G.*) AS Good, COUNT(B.*) AS Bad
FROM table_good G
FULL OUTER JOIN table_bad B
ON G.widget = B.widget AND A.Good = B.Bad
WHERE (G.widget = 'Widget A' OR B.Widget = 'Widget A')
AND (G.Good = 'Y' OR B.Good = 'Y')