Reputation: 3361
I'm having trouble with a query I'm trying to write in oracle.
Basically I want to get the count of two tables that have the same provider list. I can run the query individually but not sure how to do it in one shot.
Here's a example:
SELECT name, COUNT(name)
FROM table1
group by name
This gives me a list of names and a count beside them. If I run the same command but on table2(changing the from statement), it works fine. What I want to do is have a query that takes count from table1 and substracts it from count from table2.
How can I do it? I have tried to do nested selects and so on but can't seem to get it to work.
Upvotes: 1
Views: 94
Reputation: 231711
One option assuming that the name
values in both tables are identical would be
SELECT t1.name, t2.cnt - t1.cnt diff
FROM( SELECT name, COUNT(name) cnt
FROM table1
group by name ) t1,
( SELECT name, COUNT(name) cnt
FROM table2
group by name ) t2
WHERE t1.name = t2.name
If you want to handle the case where one table has a name
that the other doesn't but you don't know which table has the extra name (and assuming that you want to say that the other table has a cnt
of 0 for that name
)
SELECT coalesce(t1.name, t2.name) name,
nvl(t1.cnt, 0 ) t1_cnt,
nvl(t2.cnt, 0 ) t2_cnt,
nvl(t2.cnt,0) - nvl(t1.cnt,0) diff
FROM( SELECT name, COUNT(name) AS cnt
FROM table1
group by table1.name ) t1
full outer join
( SELECT name, COUNT(name) AS cnt
FROM table2
group by table2.name ) t2
on( t1.name = t2.name )
which you can see in this SQLFiddle
Upvotes: 4