从这个表T2中,我需要通过ID选择每个组中最早的日期,其中Prog是' YY'并在DATEDIFF
中使用EDate
:
+----+-----------+-----------+------+
| ID | SDate | Edate | Prog |
+----+-----------+-----------+------+
| 1 | 4/12/2016 | 5/18/2016 | XX |
| 1 | 4/1/2016 | 4/4/2016 | YY |
| 1 | 5/23/2016 | 5/28/2016 | YY |
| 2 | 9/21/2016 | 9/26/2016 | XX |
| 2 | 8/7/2016 | 8/9/2016 | YY |
| 3 | 8/2/2015 | 8/12/2015 | YY |
| 3 | 4/12/2015 | 4/18/2015 | YY |
+----+-----------+-----------+------+
然后将表T1中的汇总级别显示为期望输出:
+----+------+-----+-----------+------+
| ID | Name | Age | SDate | Days |
+----+------+-----+-----------+------+
| 1 | A | 52 | 4/1/2016 | 3 |
| 2 | B | 11 | 8/7/2016 | 2 |
| 3 | C | 24 | 4/12/2015 | 6 |
+----+------+-----+-----------+------+
尝试:
SELECT
T1.ID,
T1.Name,
T1.Age,
MIN(T2.SDate) AS [SDate],
--DATEDIFF(day,MIN(T2.SDate),T2.EDate) AS [Days]
FROM T1
INNER JOIN T2
ON T1.ID=T2.ID
WHERE T2.Prog='YY'
GROUP BY
T1.ID,
T1.Name,
T1.Age
我为Days注释了DATEDIFF函数,因为我不确定如何制定它。显然,像DATEDIFF(day,SELECT MIN(SDate) FROM T2 WHERE Prog='YY','Another Date')
这样的东西不会起作用,因为我会得到一个整体的MIN(SDate),它不会被ID分割,我不能SELECT ID,MIN(SDate) FROM T2 WHERE Prog='YY' GROUP BY ID
内部子查询,因为DATEDIFF只接受Date字段。
那么在这种情况下,如何为每个分组ID提取MIN(SDate)并为相应的Edate计算DATEDIFF?
答案 0 :(得分:1)
使用min
窗口函数获取每个id的最小日期,并使用它来计算日期差异。
SELECT ID,NAME,Age,DATEDIFF(DD,SDate,EDate)
FROM (
SELECT
T1.ID,
T1.Name,
T1.Age,
MIN(CASE WHEN T2.PROG = 'YY' THEN T2.SDate END) OVER(PARTITION BY T2.ID) AS [SDate],
T2.EDate
FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
) x
答案 1 :(得分:0)
使用MIN
作为窗口函数:
SELECT T1.ID,
T1.Name,
T1.Age,
DATEDIFF(day,
MIN(T2.SDate) OVER PARTITION BY (T1.ID, T1.Name, T1.Age),
T2.EDate) AS [Days]
FROM T1
INNER JOIN T2
ON T1.ID = T2.ID
WHERE T2.Prog = 'YY'