在日期值

时间:2017-01-27 22:05:28

标签: tsql null

我必须通过Max(StartDate)选择一组记录,并且有多个记录具有相同的StartDate但不同的EndDate我想选择具有NULL EndDate的记录超过具有实际日期的值。

SELECT UPC, DocumentNumber, MAX(StartDate) AS 'StartDate'
                FROM #tbDupRecs
                --WHERE EndDate = CASE EndDate WHEN NULL THEN NULL ELSE EndDate END
            GROUP BY UPC, DocumentNumber
            Order By UPC, DocumentNumber, StartDate

当我尝试包含类似EndDate之类的内容时,我会收到错误,因为我无法在Select语句或Group By等中使用它...我尝试的所有内容(如上所述)都选择带有日期的记录.... / p>

1 个答案:

答案 0 :(得分:1)

我认为这应该有用......它会为您分组的每组记录提供一个RN,并获得最高记录。

with cte as(
SELECT 
    UPC, 
    DocumentNumber, 
    StartDate,
    row_number over (partition by UPC, DocumentNumber order by case when StartDate is null then '12/31/2999' else StartDate end desc) as rn
FROM #tbDupRecs)

select * from cte where rn = 1

OR

SELECT 
    UPC, 
    DocumentNumber, 
    StartDate
FROM #tbDupRecs
WHERE EXISTS (SELECT UPC, DocumentNumber, max(isnull(StartDate,'12/31/2999')) FROM #tbDupRecs group by UPC, DocumentNumber)

OR

SELECT 
    r.UPC, 
    r.DocumentNumber, 
    r.StartDate
FROM #tbDupRecs r
INNER JOIN 
    (SELECT UPC, DocumentNumber, max(isnull(StartDate,'12/31/2999')) 
    FROM #tbDupRecs 
    group by UPC, DocumentNumber) r2 on r.UPC = r2.UPC and r.DocumentNumber = r2.DocumentNumber and isnull(r.StartDate,'12/31/2999') = isnull(r2.StartDate,'12/31/2999')