Need help in building MYSQL query to count two content from single row/table

前端 未结 3 440
独厮守ぢ
独厮守ぢ 2021-01-16 18:49

I\'m trying to get count of two set of data which is listed under same table name, with specific date range.

Table \'Event\'

u_id event  Create
123  F_lo         


        
相关标签:
3条回答
  • 2021-01-16 19:08

    Query

    SELECT t.`Create`, 
    SUM(CASE WHEN t.`F_log` > 0 THEN 1 ELSE 0 END) as `F_log`,
    SUM(CASE WHEN t.`C_log` > 0 THEN 1 ELSE 0 END) as `C_log` FROM(
        select `u_id`, `Create`,
        SUM(CASE WHEN `event` = 'F_log' THEN 1 ELSE 0 END) AS `F_log`,
        SUM(CASE WHEN `event` = 'C_log' THEN 1 ELSE 0 END) AS `C_log`
        FROM `Event`
        GROUP BY `u_id`, `Create`
    )t
    GROUP BY t.`Create`;
    
    0 讨论(0)
  • 2021-01-16 19:13

    select to_char(cast(created as date),'YYYY-MM-DD') as Report_date, count(distinct(case when event_type in ('Flash C Log') then user_id else 0 end)) as Flash_Log, count(distinct(case when (event_type = 'Client C Log') then user_id else 0 end)) as Client_Log from events e where created between '25-SEP-16' and '27-SEP-16' group by to_char(cast(created as date),'YYYY-MM-DD') order by to_char(cast(created as date),'YYYY-MM-DD');

    0 讨论(0)
  • 2021-01-16 19:22

    The COUNTs has to be done in separate subqueries. This should work.

    SELECT DISTINCT E.created,F.flash,C.client
    FROM events E
    LEFT JOIN (
        SELECT created,COUNT(DISTINCT user_id) as flash
        FROM events
        WHERE event_type LIKE 'Flash C log'
        GROUP BY created
    ) F
    ON F.created = E.created
    LEFT JOIN (
        SELECT Created,COUNT(DISTINCT user_id) as client
        FROM events
        WHERE event_type LIKE 'Client C log'
        GROUP BY created
    ) C
    ON C.created = E.created
    WHERE E.created BETWEEN '2016-09-25' AND '2016-09-27'
    

    Fiddle with results

    EDIT: As of your comments, I have made a question that adds a column of the distinct combined userids with clients and flash logs for each date. I added a little data to that fiddle to test.

    SELECT DISTINCT E.created,F.flash,C.client,FC.combined
    FROM events E
    LEFT JOIN (
        SELECT created,COUNT(DISTINCT user_id) as flash
        FROM events
        WHERE event_type LIKE 'Flash C log'
        GROUP BY created
    ) F
    ON F.created = E.created
    LEFT JOIN (
        SELECT Created,COUNT(DISTINCT user_id) as client
        FROM events
        WHERE event_type LIKE 'Client C log'
        GROUP BY created
    ) C
    ON C.created = E.created
    LEFT JOIN (
        SELECT Created,COUNT(DISTINCT user_id) as combined
        FROM events
        WHERE event_type LIKE 'Client C log' OR event_type LIKE 'Flash C log'
        GROUP BY created
    ) FC
    ON FC.created = E.created
    WHERE E.created BETWEEN '2016-09-25' AND '2016-09-27'
    

    SQL Fiddle for answer 2

    0 讨论(0)
提交回复
热议问题