For a table like this named Activity
:
player_id | device_id | event_date | games_played |
---|---|---|---|
1 | 2 | 2016-03-01 | 5 |
1 | 2 | 2016-03-02 | 6 |
2 | 3 | 2017-06-25 | 1 |
3 | 1 | 2016-02-02 | 0 |
3 | 4 | 2018-07-03 | 5 |
I wonder why the following query only returns the result on the first row:
select player_id, datediff(event_date, min(event_date)) as date_diff
from Activity
Returns:
player_id | date_diff |
---|---|
1 | 28 |
I was expecting the fourth row will be returned as it has the minimum event_date
, something like
player_id | date_diff |
---|---|
2 | 0 |
2
Answers
I think you should have 3 separate
select
query, one to find the min event date in the entire table, one to add the result as a column in the query result, final one to calculate the date differenceFrom your sample data, running the query would get:
When I ran the query in your question, I got an error:
min
is an aggregate function and that’s why a GROUP BY is required. However that won’t give you the result you want.In order to get difference between EVENT_DATE and minimum EVENT_DATE for each row, you can use a separate SELECT as a generated column.
Above query returned following result:
Refer to this db<>fiddle