W
W
w_b_x2016-08-25 19:15:52
PHP
w_b_x, 2016-08-25 19:15:52

How to use GROUP BY in one QUERY with multiple SELECT?

Hello!
Roughly speaking, there is such a request:

SELECT  
(SELECT COUNT(*) FROM  `l_sites`) AS tot_user,
(SELECT COUNT(*) FROM  `l_users`) AS tot_user2,
(SELECT COUNT(*) FROM  `l_leads`) AS tot_user3

Works great.
But what if I do not need the total amount, but the amount for each day?
3 separate queries would look like this:
SELECT `date`, COUNT(*) AS tot_user FROM  `l_sites` GROUP BY `date`
SELECT `date`, COUNT(*) AS tot_user2 FROM  `l_users` GROUP BY `date`
SELECT `date`, COUNT(*) AS tot_user3 FROM  `l_leads` GROUP BY `date`

Individually they work fine, but how do I combine them into one query?
It is necessary, because through PHP I display all this in a table through WHILE.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
idShura, 2016-08-25
@w_b_x

SELECT `date`, COUNT(*) AS cnt, 'tot_user' as user FROM  `l_sites` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'tot_user2' as user FROM  `l_users` GROUP BY `date`
union all
SELECT `date`, COUNT(*) AS cnt, 'tot_user3' as user FROM  `l_leads` GROUP BY `date`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question