TSQL在where子句中选择最小日期

时间:2017-08-03 08:12:18

标签: sql sql-server tsql

以下是一个示例数据集:

ID  DATE       STATUS        DURATIONTIME
1  30-08-2017  Done          220
1  30-08-2017  In progress   100
1  29-08-2017  In progress   50
1  28-08-2017  New           10
2  30-08-2017  Done          200
2  30-08-2017  In progress   100
2  29-08-2017  In progress   60
2  29-08-2017  New           50
2  28-08-2017  New           10

预期结果:

1    60
2    120

我们想要计算状态未完成时的持续时间总和以及状态是否正在进行,然后只计算最早日期的持续时间。

这是我尝试的查询:

SELECT        ID, SUM(DURATIONTIME) 
FROM          MYDB
WHERE         STATUS <> 'Done'
            AND DURATIONTIME = CASE
                WHEN (STATUS = 'In progress' AND DATE <> min(DATE)) 
                THEN 0
                ELSE DURATIONTIME END 
GROUP BY ID ASC

但是查询失败了...知道如何重写这个查询吗?

1 个答案:

答案 0 :(得分:3)

使用DENSE_RANK窗口功能

SELECT ID,
       Sum(DURATIONTIME)
FROM   (SELECT DENSE_RANK()OVER(partition BY ID, Status ORDER BY DATE asc) Rn,*
        FROM   yourtable
        WHERE  Status in ('New','In progress')) a
WHERE  (Rn = 1 and Status = 'In progress') or Status = 'New'
GROUP  BY ID