简体   繁体   中英

SQL Statement - Create a Report with three totals

Having a little trouble creating this query in mysql. I think i'm missing something obvious.

I have a Users table, which has a column called device (Android, iOs, Windows are the 3 possible values). I would like to create a report that tells me how many users registered for each day (so group by the date) but for each device (so a total in each column).

I was able to make a query that tells me how many users registered as a total for the first column, but couldn't get the sub-queries working in the next few columns.

Right now my working query I tried is this:

SELECT COUNT(u.userid) 'Total Users', date(u.datecreated) 'Day'
FROM Users
GROUP BY date(u.datecreated)
ORDER BY u.datecreated DESC

This produces a nice aggregated report for me that shows the # of users who were created each day (the total is one column, the date for the total is the second column)

So expanding on the working query above, I tried making a subquery like this but it keeps producing '1' as the result for the new column.

select count(distinct u.userid) 'Total Users', 
(select count(u1.userid) from Users u1 where u1.datecreated = u1.datecreated and u.device = 'android' group by u1.datecreated) 'Android Users',
date(u.datecreated) 'Day'
from Users u
group by date(u.datecreated)
order by u.datecreated desc

How could I get that inner query to produce the total number of android users for that day?

For each type of device you can count subtotal using CASE statement.

Try this:

SELECT
    COUNT(u.userid) 'Total Users',
    SUM(CASE WHEN device = 'android' THEN 1 END) Android,
    SUM(CASE WHEN device = 'iOs' THEN 1 END) iOs,
    SUM(CASE WHEN device = 'Windows' THEN 1 END) Windows,
    date(u.datecreated) 'Day'
FROM Users
GROUP BY date(u.datecreated)
ORDER BY date(u.datecreated) DESC

Just group by on device as well, not just on the date:

SELECT COUNT(u.userid) 'Total Users', date(u.datecreated) 'Day', device
FROM Users
GROUP BY date(u.datecreated), device
ORDER BY u.datecreated DESC

You can add with rollup modifier to the end, if you want a separate line to hold total by day as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM