1

次の問題に対して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)

ご覧のとおり、2 つの異なる行と 2 つの列の値の違いが必要です。

私は試した

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

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 に答える