W
W
w_b_x2016-08-25 22:22:35
MySQL
w_b_x, 2016-08-25 22:22:35

GROUP BY eats data, why?

Hello!
In general, today I asked a question here about grouping several SELECTs. Select with GROUP BY by date from 3 tables, to be exact. As a result, I received an answer, but found a strange work.
To the point.
If I run this code:

SELECT `date`,
       case when `user` = 'new_sites'  then cnt else 0 end as new_sites,
       case when `user` = 'new_users' then cnt else 0 end as new_users,
       case when `user` = 'new_leads' then cnt else 0 end as new_leads
FROM (
SELECT `date`, COUNT(*) AS cnt, 'new_sites' as user FROM  `l_sites` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'new_users' as user FROM  `l_users` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'new_leads' as user FROM  `l_leads` GROUP BY `date`
) as T

The result is this:
afbc0e69e503438a8b1305e6eaf113de.pngThe dates are repeated, but in general everything is fine. It remains to add GROUP BY `date` at the end and it's over - I thought.
I write the following code:
SELECT `date`,
       case when `user` = 'new_sites'  then cnt else 0 end as new_sites,
       case when `user` = 'new_users' then cnt else 0 end as new_users,
       case when `user` = 'new_leads' then cnt else 0 end as new_leads
FROM (
SELECT `date`, COUNT(*) AS cnt, 'new_sites' as user FROM  `l_sites` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'new_users' as user FROM  `l_users` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'new_leads' as user FROM  `l_leads` GROUP BY `date`
) as T GROUP BY `date`

As a result, we get:
a1255b53d18549bf8ece6d1275706d3a.png
Please note that in the first case there are 3 units in the rightmost column, in the second case there are only two with grouping. GROUP BY eats data for 2016-08-24. By the way, the situation is similar with the column in the center.
What is the problem and how to solve?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Котик Антон, 2016-08-25
@w_b_x

Во внешнем запросе тоже должны быть функции COUNT() иначе, как GROUP BY догадается, что нужно сделать с группами.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question