简体   繁体   中英

How to group records by dates in SQL Server

Let's look at the following table

Name    TIMESTAMP   STATUS

Task1   01-01-2019  COMPLETE
Task1   01-01-2019  COMPLETE
Task2   01-01-2019  COMPLETE
Task3   02-01-2019  NOT COMPLETE
Task4   01-01-2019  COMPLETE    
Task4   02-01-2019  COMPLETE

What I want is the output to be like this:

Date       TaskName    How many completed?

January    Task1           2
January    Task2           1
January    Task3           0
January    Task4           1
February   Task1           0
February   Task2           0
February   Task3           0
February   Task4           1

I'm having troubles on figuring out how to group the count each task to a particular date. My table has over 10 tasks and around 100k rows and they need to be grouped by dates so we can see how many tasks were successfully completed for each month.

select DateName(month, DateAdd(month, month([TIMESTAMP]),0)-1) as 'Month', 
count(TaskName) as 'Total Processed' 
from myTable
where YEAR([TIMESTAMP]) = 2019 and TaskName = 'Task1'
group by month([TIMESTAMP]);

So far I know this will give me the total count of times Task1 was completed for each month in 2019, but I am struggling on how to put each task in this outputted table with their respective names. Can anyone suggest on how I can proceed? Any guidance would be great!

You can use the following query:

SELECT DATENAME(month,[Timestamp]), Name,
       SUM(CASE WHEN [STATUS] = 'Completed' THEN 1 ELSE 0 END) as [Completed]
FROM Table1
GROUP BY DATENAME(month,[Timestamp]), Name
ORDER BY DATENAME(month,[Timestamp]), Name

  • DATENAME(month,[Timestamp]) will get the month name
  • SUM(CASE WHEN [STATUS] = 'Completed' THEN 1 ELSE 0 END) will return how much task are completed

Try this.

select 
    case 
        when to_char(timestamp, 'MM') = '01' then 'January'
        when to_char(timestamp, 'MM') = '02' then 'Febuary'
        when to_char(timestamp, 'MM') = '03' then 'March'
        when to_char(timestamp, 'MM') = '04' then 'April'
    end as month,name, count(status)
    from myTable
    group by month,name
    order by timestamp;

Use a cross join to generate the rows and then left join to bring in the data:

select m.mm, n.name,
       sum(case when t.status = 'COMPLETE' then 1 else 0 end) as num_completed
from (values (convert(date, '2019-01-01'),
              convert(date, '2019-02-01')
     ) m(mm) cross join
     (select distinct name
      from t
     ) n left join
     t
     on t.name = n.name and
        t.timestamp >= m.mm and
        t.timestamp < dateadd(month, 1, m.mm)
group by m.mm, n.name;

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