我有以下sql查询
GO
SELECT @StartDate= table1.StartDate, @EndDate= table2.EndDate from table1 join table2
SELECT @StartDate= table2.StartDate, @EndDate= table3.EndDate from table2 join table3
SELECT @StartDate= table3.StartDate, @EndDate= table4.EndDate from table3 join table4
基本上,如果最后一个查询不为null,那么这将是@StartDate
和@EndDate
的最终值。对此最好的方法是什么,我正在考虑使用ISNULL
,COALESCE
或CASE
WHEN
答案 0 :(得分:2)
我认为不需要3个查询来获得所需的结果。 with open("/Users/jj/Desktop/Courtney_fan.txt") as f:
sd = f.read()
sd_list = eval(sd)
函数仅评估一次。 ISNULL
表达式可以多次评估。
COALESCE
答案 1 :(得分:0)
DECLARE @DataSource TABLE
(
[RecordID] TINYINT PRIMARY KEY
);
DECLARE @DataSourceDates01 TABLE
(
[RecordID] TINYINT PRIMARY KEY
,[StartDate] DATETIME2
,[EndDate] DATETIME2
);
DECLARE @DataSourceDates02 TABLE
(
[RecordID] TINYINT PRIMARY KEY
,[StartDate] DATETIME2
,[EndDate] DATETIME2
);
DECLARE @DataSourceDates03 TABLE
(
[RecordID] TINYINT PRIMARY KEY
,[StartDate] DATETIME2
,[EndDate] DATETIME2
);
INSERT INTO @DataSource ([RecordID])
VALUES (1), (2), (3);
INSERT INTO @DataSourceDates01 ([RecordID], [StartDate], [EndDate])
VALUES (1, GETUTCDATE(), GETUTCDATE());
INSERT INTO @DataSourceDates02 ([RecordID], [StartDate], [EndDate])
VALUES (1, GETUTCDATE(), GETUTCDATE())
,(2, GETUTCDATE(), GETUTCDATE());
INSERT INTO @DataSourceDates03 ([RecordID], [StartDate], [EndDate])
VALUES (1, GETUTCDATE(), GETUTCDATE())
,(2, GETUTCDATE(), GETUTCDATE())
,(3, GETUTCDATE(), GETUTCDATE());
SELECT DS.[RecordID]
,COALESCE(DS1.[StartDate], DS2.[StartDate], DS3.[StartDate]) AS [StartDate]
,COALESCE(DS1.[EndDate], DS2.[EndDate], DS3.[EndDate]) AS [EndDate]
FROM @DataSource DS
LEFT JOIN @DataSourceDates01 DS1
ON DS.[RecordID] = DS1.[RecordID]
LEFT JOIN @DataSourceDates02 DS2
ON DS.[RecordID] = DS2.[RecordID]
LEFT JOIN @DataSourceDates03 DS3
ON DS.[RecordID] = DS3.[RecordID];