Reputation: 151
I have 2 tables in sql, and i am doing a query:
in the first query i am counting the data from a date
In the secont query i am counting the data from a the same date
And in the 3 query i am doing a inner join, but i need show the data that i have in the query
20101120 26 19
But i have:
20101120 313 313
I have the example in:
http://sqlfiddle.com/#!4/e61fc/2
Who can help me?
What is the problem?
I can do it with a join?
Or the problem is the join?
Upvotes: 0
Views: 74
Reputation: 146239
The problem is your data. There are only two services in each table.
So
(s.id_service = b.id_service and
b.id_date = s.id_date_sus)
is not joining on a unique key.
When that happens we get a cartesian product, in which every record on one side of the join is paired to every record on the other side of the join. For service_id=1
that produces (19*15) rows; for service_id=2
that produces (4*7) rows. Now, 285+28=313, which explains the count which troubles you.
The solution is to run the two counts as separate sub-queries and then join them in the main query:
select s.id_date_sus, s.cnt as s_cnt, b.cnt as b_cnt
from
( select s.id_date_sus, count(*) cnt
from suscription s
group by s.id_date_sus) s
join ( select b.id_date, count(*) cnt
from billing b
group by b.id_date) b
on (s.id_date_sus = b.id_date);
Here is my re-work of your SQL Fiddle.
Upvotes: 0
Reputation: 70648
SELECT A.id_date_sus AS id_date,
A.N1,
B.N2
FROM (SELECT id_date_sus,
COUNT(id_date_sus) AS N1
FROM suscription
GROUP BY id_date_sus) A
LEFT JOIN (SELECT id_date,
COUNT(id_date) AS N2
FROM billing
GROUP BY id_date) B
ON A.id_date_sus = B.id_date;
Upvotes: 1
Reputation: 707
If you use oracle db, You can do something like:
with s1 as
(select id_date_sus, count(id_date_sus) c1
from suscription
group by id_date_sus),
s2 as
(select id_date, count(id_date) c2
from billing
group by id_date)
select s1.id_date_sus, s1.c1, s2.c2 from s1, s2 where s1.id_date_sus = s2.id_date
Upvotes: 0