Answer the question
In order to leave comments, you need to log in
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
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`
Answer the question
In order to leave comments, you need to log in
Во внешнем запросе тоже должны быть функции COUNT() иначе, как GROUP BY догадается, что нужно сделать с группами.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question