开发者

Oracle/SQL - Combining counts from 'unrelated' unrelated tables

开发者 https://www.devze.com 2023-02-26 20:01 出处:网络
Let\'s assume I two tables GOOD and BAD that stores records for widget production.My tables look like this

Let's assume I two tables GOOD and BAD that stores records for widget production. My tables look like this

Widget      Good
----------------
Widget A    Y
Widget A    Y
Widget B    Y

Widget      Bad
----------------
Widget A    Y
Widget B    Y

I have these two basic queries

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'

These would result in two tables like this

good
----
2

bad
---
1

I would like to combine these into a single query where I would get back a table with a single record that looks like this

good    bad
-----------
2       1

Can someone point me how to do this. I thought doing a union an开发者_开发百科d setting up fake columns in the other tables selects would do it, but I got the right table schema back, but had two seperate records.

Thanks!


Try this:

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  


Another way is using a 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')
0

精彩评论

暂无评论...
验证码 换一张
取 消