SQL查询 - 两行和两列的值之间的差异

时间:2013-10-05 03:09:12

标签: sql sql-server sql-server-2008

我正在努力使这个工作,使用T-SQL查询(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 个答案:

答案 0 :(得分: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 FIDDLE

答案 1 :(得分:0)

尝试类似的东西。它应该给你你想要的差异。我在第一部分中获得每个产品的第一行,然后使用下一个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

答案 2 :(得分: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   

答案 3 :(得分:-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