简体   繁体   中英

MySQL select count from different columns using also group by

在此处输入图像描述

I have this table called tasks. I want to fetch count of the total task of each assign_date and on that date how many complete task by complete_date per user.

I want something like below

    [{
      user_id:1 ,
      assign_date / compete_date : 2019-09-04,
     assign_task : 2,
    complete_task: 1
    },
{
      user_id:1 ,
      assign_date / compete_date : 2019-09-19,
     assign_task : 1,
    complete_task: 2
    }
]

Here's your query. using union all will get the count on both assigned and complete dates

select user_id
    , complete_date as [assign_date / compete_date]
    , sum(case when t1.s = 'assigned' then 1 else 0 end) as assign_task
    , sum(case when t1.s = 'complete' then 1 else 0 end) as complete_task
from
    (select user_Id, complete_date, 'complete' as s from task 
    union all
    select user_Id, assign_date, 'assigned' as s from task) t1
group by t1.complete_date, t1.user_id

You can try below -

select user_id,date, count(assign_date) assign_task,count(compete_date) complete_task
from tablename
group by user_id,date

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