你的問題是有點不清楚,但我認爲這將指向你在生產方向。 SQL被設計爲對一組行執行操作,而不是一次循環處理一行。以下代碼將在每個日期/時間將您的數據關聯到每一對插槽的一行中。您可以使用CASE
表達,如圖所示,添加一列表示該行的狀態,然後你可以添加一個WHERE
條款,未顯示,執行任何額外的濾波。
-- Sample data.
declare @Samples as Table (SampleId Int, Slot Int, EventDate Date, StartTime Time(0), EndTime Time(0), Action VarChar(10));
insert into @Samples (SampleId, Slot, EventDate, StartTime, EndTime, Action) values
(200, 1, '20150501', '00:00:00', '00:30:00', NULL),
(201, 2, '20150501', '00:00:00', '00:30:00', NULL),
(202, 1, '20150501', '00:30:00', '01:00:00', 'A'),
(203, 2, '20150501', '00:30:00', '01:00:00', NULL),
(204, 1, '20150501', '01:00:00', '01:30:00', NULL),
(205, 2, '20150501', '01:00:00', '01:30:00', 'A'),
(206, 1, '20150501', '01:30:00', '02:00:00', 'B'),
(207, 2, '20150501', '01:30:00', '02:00:00', 'B');
select * from @Samples;
-- Data correleated for each date/time.
select Slot1.EventDate, Slot1.StartTime, Slot1.EndTime,
Slot1.Action as Action1, Slot2.Action as Action2,
Coalesce(Slot1.Action, Slot2.Action) as SummaryAction,
case when Slot1.Action = Slot2.Action then 'ERROR!' else 'Okay.' end as Status
from @Samples as Slot1 inner join
@Samples as Slot2 on Slot2.EventDate = Slot1.EventDate and Slot2.StartTime = Slot1.StartTime and
Slot1.Slot = 1 and Slot2.Slot = 2;
它剛剛找到我,我可能正在尋找像SQL循環中的東西。你可以選擇一個表並遍歷其中的每一行,並將它們中的一些傳遞到使用TSQL中的循環的結果表中? – IvanN
可以檢查不在子查詢中的三列,但不是沒有理解您的要求拳頭。 – Tim3880