Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

sql server - Partition and group by query

I have table containing the columns: 1. ClockifyId, 2. StartTime EndTime of every Task 3. Date. 4. Duration

The image is attached below My goal is to write query to calculate the total duration of every user(which is ClockifyId) of every date. As One User can have multiple task in one day, I wanted to sum duration of all those task. In short, I wanted to have total task duration of every user(which is clockifyid) of every date.
enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of details missing here, but this should get you close enough.

The first thing you need to do is convert the StartTime and EndTime to datetime fields if they aren't already. Doing a DATEDIFF on them allows you to figure out per record what the difference in minutes is. You can change the unit of measure as needed.

Once you do that, you use the SUM() which is an aggregate function. This makes it necessary to use the GROUP BY. You then group by which ever fields, in this case the ClockifyId and the StartTime as a date. You have to do it as a date without the datetime or you will get multiple rows back for a single Clockify record in a day.

SELECT 
      ClockifyId
    , SUM(DATEDIFF(mi, CAST(StartTime AS datetime), CAST(EndTime AS datetime))) AS DurationInMinutes
    , CAST(StartTime AS date)
FROM TableName
GROUP BY
      ClockifyId
    , CAST(StartTime AS date)

It's worth noting that this assumes there is always a valid StartTime and EndTime. This will throw some errors if those fields have nulls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...