この質問はSQL Serverに関連しています。私は、このSQL文を実行すると2行の秒の差を返すSQL
id size batch code product code additiontime
--------------------------------------------------------
1 91 55555 BigD Red 2017-05-15 13:00:00
2 91 55555 BigD Red 2017-05-15 13:00:05
3 94 55555 BigD Red 2017-05-15 13:00:15
4 91 44444 BigD Blue 2017-05-15 14:10:00
5 92 44444 BigD Blue 2017-05-15 14:15:00
6 93 44444 BigD Blue 2017-05-15 14:20:00
7 94 44444 BigD Blue 2017-05-15 14:30:00
8 91 33333 BigD Orange 2017-05-15 15:00:00
9 91 33333 BigD Orange 2017-05-15 15:00:10
10 94 33333 BigD Orange 2017-05-15 15:00:15
:そう
id size batch code product code additiontime
--------------------------------------------------------
1 91 55555 BigD Red 2017-05-15 13:00:00
2 91 55555 BigD Red 2017-05-15 13:00:05
8 91 33333 BigD Orange 2017-05-15 15:00:00
9 91 33333 BigD Orange 2017-05-15 15:00:10
私は上記のクエリを変更したいと思います:
select *
from mytable y1
where size = 91
and not exists (select 1
from mytable y2
where y1.productcode = y2.productcode and y2.size = 92)
を私は次のような結果を得る私は、次の表を持っていますバッチコードごとに1行が表示され、各バッチコードグループの1番目と2番目のレコードの間の秒数を示す追加の列が追加されます。
id size batch code product code additiontime seconds difference
--------------------------------------------------------------------------------------
1 91 55555 BigD Red 2017-05-15 13:00:00 5
8 91 33333 BigD Orange 2017-05-15 15:00:00 10
は、私はほとんどのトリックを行い、以下のSQLを、試してみましたが、それは代わりにバッチコードごとに1つの複数の行を返します。
WITH rows AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY AdditionTime) AS rn
FROM
mytable y1
WHERE
size = 91
AND NOT EXISTS (SELECT *
FROM mytable y2
WHERE y1.productcode = y2.productcode AND y2.size = 92)
)
SELECT DATEDIFF(second, mc.AdditionTime, mp.AdditionTime)
FROM rows mc
JOIN rows mp ON mc.rn = mp.rn - 1
マイSQLの知識は素晴らしいではありません。正しい結果を生み出すことは可能だと確信していますが、私は成功していないすべての方法を試しました。どのポインタについても事前に感謝します。
あなたはいつも2つの行を持っていると思いますか?もしそうなら、どのようにdiffを計算したいですか? – Tanner
SQL Server 2012以降を使用している場合は、[ウィンドウ関数](https://www.simple-talk.com/sql/learn-sql-server/window-functions-in-sql-server/)を使用して、 。 over節を使用すると、前の行を選択して適切なDATEDIFFを実行できます。 – PacoDePaco
@Tanner - 常に2行が必要です。 –