I have a table with the following structure and example records:
I want to figure out how to get the difference between the two earliest created_at records for each name. It is a possibility the name only has one record, in which case any default value is okay, like 0, -1, or NULL. Running it on the above record I would anticipate a result like so:
nameA, 31
nameB, 59
nameC, -1
I can't think of any clean ways to do this purely in SQL. I thought about joining the table on itself, grouping on name, and selecting the min created_at from the first join, but I don't know how to then select the second minimum to bring it down to a single record.
Thanks
One option, using a CTE with ROW_NUMBER
:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY created_at) rn
FROM yourTable
)
SELECT
name,
DATEDIFF(MAX(created_at), MIN(created_at)) AS diff_in_days
FROM cte
WHERE rn <= 2
GROUP BY
name
ORDER BY
name;
If you mysql version didn't support window function you can try to use correlated-subquery make row number.
Query 1 :
SELECT t1.name,DATEDIFF(t1.max_dt,t1.min_dt) value
FROM (
select name,
max(create_date) max_dt,
min(create_date) min_dt
from (
SELECT *,(SELECT COUNT(*)
FROM T tt
WHERE tt.name = t1.name and t1.create_date >= tt.create_date) rn
FROM T t1
) t1
where rn <= 2
group by name
) t1
Results :
| name | value |
|-------|-------|
| NameA | 31 |
| NameB | 59 |
| NameC | 0 |
I would use lead()
and `row_number():
select t.name,
datediff(next_created_at, created_at) as diff_days
from (select t.*,
lead(created_at) over (partition by name order by created_at) as next_created_at,
row_number() over (partition by name order by created_at) as seqnum
from t
) t
where seqnum = 1;
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.