0

I need to get sum of days. The sum should be a number. For summing should be taken only unique dates. In below table there are 3 records for userid 1. I need to get result equal 2 because he worked 2 days, 04.06.2018 and 05.06.2018.

UserID  Date
1       04.06.2018 10:45:11
1       04.06.2018 17:15:11
1       05.06.2018 09:15:33

Desired result is:

UserID  TotalDays
1       2

How to achive that? Thanks!

2 Answers 2

1

If you want to get TotalDays per user:

SELECT UserId, COUNT(DISTINCT DATEDIFF(DAY, 0, Date)) TotalDays
FROM UserDate
GROUP BY UserID
Sign up to request clarification or add additional context in comments.

Comments

0

I did it myself.

-- Bad query
SELECT count(distinct CAST(Date as int))

-- Slightly better
SELECT count(distinct cast(cast(Date as float) as int))

Note: It's not recommended to cast straight to an int, as MSSQL rounds the value up if you're past mid day!

4 Comments

Be careful, CAST(Date as int) can return the same value for 2 dates with different days
could you provide an example?
Just run this on your table: SELECT Date, CAST(Date as int) FROM table. In your example, 2nd and 3rd dates have different days, but the query will return 43254 for both.
Yes it's true, but I don't care about time but only date. Although, my approach isn't as elegant as yours. I changed my procedure, thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.