我认为您的问题源于您想按天分组,但您的专栏Date_occure
也在存储时间。我不是 100% 确定您需要的确切输出,但这应该可以为您提供所需的一切:
WITH CTE AS
( SELECT [File_ID],
[Status],
Date_Occure,
Occurrences = COUNT(CASE WHEN [Status] IN (1, 2, 3) THEN [Status] END) OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE)),
RowNumber = ROW_NUMBER() OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE) ORDER BY Date_Occure, [Status] DESC)
FROM T
)
SELECT [File_ID], [Status], Date_Occure, Occurrences
FROM CTE
WHERE RowNumber = 1;
关键是分区,CAST(Date_Occure AS DATE)
而不仅仅是date_occure
.
一个简化的版本是:
SELECT [File_ID],
Date_Occure = MIN(Date_Occure),
Occurrences = COUNT(CASE WHEN [Status] IN (1, 2, 3) THEN [Status] END)
FROM T
GROUP BY [File_ID], CAST(Date_Occure AS DATE);
编辑
我刚刚重新阅读了这个问题,并认为我现在理解了标准。
如果所有三个状态(1、2、3)都必须按顺序出现,那么您可以使用它:
SELECT [File_ID],
Date_Occure = MIN(Date_Occure)
FROM T
WHERE NOT EXISTS
( SELECT 1
FROM T T2
WHERE T2.[File_ID] = t.[File_ID]
AND CAST(T2.Date_Occure AS DATE) = CAST(T.Date_Occure AS DATE)
AND T2.[Status] > T.[Status]
AND T2.Date_Occure < T.Date_Occure
)
GROUP BY [File_ID]
HAVING COUNT(DISTINCT CASE WHEN [Status] IN (1, 2, 3) THEN [Status] END) = 3;
NOT EXISTS
确保不存在具有乱序状态的记录,并确保HAVING
所有 3 个状态(1、2、3)都存在。
如果您只想要特定日期的所有状态都是连续的所有文件,那么您可以使用这样的东西按状态顺序排列记录,并按日期顺序排列它们并排除存在不匹配的文件:
WITH CTE AS
( SELECT [File_ID],
[Status],
Date_Occure,
DateOrder = ROW_NUMBER() OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE) ORDER BY [Status], Date_Occure ASC),
StatusOrder = ROW_NUMBER() OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE) ORDER BY Date_Occure, [Status] ASC),
Occurrences = COUNT(*) OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE)),
RowNumber = ROW_NUMBER() OVER(PARTITION BY [File_ID], CAST(Date_Occure AS DATE) ORDER BY Date_Occure, [Status] DESC)
FROM T
)
SELECT [File_ID], [Status], Date_Occure, Occurrences
FROM CTE
WHERE RowNumber = 1
AND NOT EXISTS
( SELECT 1
FROM CTE T2
WHERE T2.[File_ID] = CTE.[File_ID]
AND CAST(T2.Date_Occure AS DATE) = CAST(CTE.Date_Occure AS DATE)
AND T2.DateOrder != T2.StatusOrder
);
SQL Fiddle 上的示例