-2

我有以下带有 ID、State 和 Date 的表结构

20130323000004  Final       3/23/2013
20130323000004  Final       3/25/2013
20130323000004  Final       3/26/2013
20130323000004  Needs Review    4/5/2013
20130323000004  Final       4/10/2013
20130323000004  Final       5/1/2013

我需要这样的结果

20130323000004  Final       3/23/2013     1
20130323000004  Final       3/25/2013     2
20130323000004  Final       3/26/2013     3
20130323000004  Needs Review    4/5/2013      1
20130323000004  Final       4/10/2013     1
20130323000004  Final       5/1/2013      21

其中最后一列是基于状态列的两条记录之间的差异。

我尝试使用 max 和 min 进行自加入,但无法获得正确的计数。你能帮我计算一下SQL中的总和吗?

谢谢

尚卡尔。

4

2 回答 2

0

试试这个,我很确定这就是你要找的东西

SELECT [ID]
  ,[State]
  ,[Date]
  ,DATEDIFF(DAY, (SELECT MIN([Date]) FROM [tableName] where [State] = a.[State]), [Date])
FROM [tableName] a
于 2013-05-16T19:17:01.180 回答
0
    SELECT ISNULL(DATEDIFF(DAY,ET.EffectiveDate,ET2.EffectiveDate),DATEDIFF(DAY,ET.EffectiveDate,GETDATE())) DayDifference,
    ET.EmployeeID,ET.EffectiveDate 
     FROM(
        SELECT ROW_NUMBER() OVER (Partition By EmployeeId Order By EffectiveDate) RowNumber,EmployeeID,EffectiveDate 
        FROM  Employee.EmployeeTransfer
     )ET
    LEFT JOIN 
    (
        SELECT ROW_NUMBER() OVER (Partition By EmployeeId Order By EffectiveDate) RowNumber,EmployeeID,EffectiveDate 
        FROM  Employee.EmployeeTransfer
    ) ET2 ON ET.EmployeeID=ET2.EmployeeID AND ET.RowNumber=ET2.RowNumber-1
    ORDER BY ET.EmployeeID, DayDifference
于 2018-01-01T05:21:41.593 回答