1

我正在努力使用 T-SQL Query (SQL SERVER 2008) 来解决以下问题:

Ky  ProductID  Start #  End #    Diff
1     100        10      12        0
2     100        14      20        2 (14 - 12)
3     100        21      25        1 (21 - 20)
4     100        30      33        5 (30 - 25) 
1     110        6       16        0
2     110        20      21        4 (20 - 16)
3     110        22      38        1 (22 - 21)

如您所见,我需要两个不同行和两列中的值之间的差异。

我试过了

with t1 
( select ROW_NUMBER() OVER (PARTITION by ProductID ORDER BY ProductID, Start# ) as KY
       , productid
       , start#
       , end# 
  from mytable)

select DATEDIFF(ss, T2.complete_dm, T1.start_dm)
   , <Keeping it simple not including all the columns which I selected..>  
FROM T1 as T2 
RIGHT OUTER JOIN T1 on T2.Ky + 1  = T1.KY  
             and T1.ProductID = T2.ProductID 

上述查询的问题是当 productID 从 100 更改为 110 时,它仍然计算差异。

非常感谢修改查询或任何更简单的解决方案的任何帮助。

谢谢

4

4 回答 4

2

您可以尝试以下代码以获得所需的结果:

select ky,Start,[End],(select  [end]  from table1 tt where (tt.ky)=(t.ky-1) and tt.ProductID=t.ProductID) [End_Prev_Row],
       case ky when 1 then 0
       else (t.start -(select  [end]  from table1 tt where (tt.ky)=(t.ky-1) and tt.ProductID=t.ProductID)) 
       end as Diff      
from table1 t

SQL 小提琴

于 2013-10-05T06:22:17.657 回答
0

尝试类似的东西。它应该给你你想要的差异。我在第一部分中获得每个产品的第一行,然后通过使用 next 递归构建Ky

with t1 
as
( 
    select  ProductID, Ky, 0 as Difference, [End#]
    from mytable where ky = 1

    union all
    select m.ProductID, m.Ky, m.[Start#] - t1.[End#] as Difference, m.[End#]
    from mytable m
    inner join t1 on m.ProductID = t1.ProductID and m.Ky = t1.Ky + 1
)

select Ky, ProductID, Difference from t1
order by ProductID, Ky
于 2013-10-05T04:01:15.993 回答
0

正如 Anup 所提到的,您的查询似乎运行良好,我只是删除了 DateDiff来计算差异,因为我假设列不是您示例中的 DATE 数据类型,我想这是问题所在,请在修改后的查询下方找到

with t1  
as  
( select ROW_NUMBER() OVER (PARTITION by ProductID ORDER BY ProductID ) as KY  
   , productid  
   , st  
   , ed  
from YourTable)  

select T1.ProductID, t1.ST,t1.ED, ISNULL(T1.st - T2.ed,0) as Diff  
FROM T1 as T2  
RIGHT OUTER JOIN T1 on T2.KY+1 = T1.KY  
         and T1.ProductID = T2.ProductID   
于 2013-10-05T04:12:24.790 回答
-1
SELECT ROW_NUMBER() OVER (PARTITION by rc.ContractID ORDER BY rc.ID) AS ROWID,rc.ID,rc2.ID,rc.ContractID,rc2.ContractID,rc.ToDate,rc2.FromDate
FROM tbl_RenewContracts rc
LEFT OUTER JOIN tbl_RenewContracts rc2
ON rc2.ID = (SELECT MAX(ID) FROM tbl_RenewContracts rcs WHERE rcs.ID < rc.ID AND rcs.ContractID = rc.ContractID) 
ORDER BY rc.ContractID

替换您的表名和列并添加计算列以获得DATEDIFF.

于 2014-01-16T13:20:09.360 回答