我想知道如何使用基于WHERE
或CASE
的其他IF
子句。我更喜欢CASE
,因为声明的其余部分很复杂,我不喜欢这种复杂性在两个地方只有一点点差异的想法。但是,我知道案例仅用于值。我在下面复制了我的问题的简单版本。
基本上,我有三张桌子。第一个包含主信息(MasterTable)。第二个包含属于主表的一对多关系(表1)。第三个是选择器列表,指示表1中的哪些记录将在此实例中使用。我想要Table2的最新记录来驱动从Table1中选择的内容,优先使用OrderNum上的SubID。
MasterTable | MasterID,OtherInfo
表1 | T1UniqueId,MasterID,SubID,Text,OrderNum
表2 | T2UniqueId,MasterID,SubID,OrderNum,Date
SELECT MasterID, OtherInfo, SubID
FROM MasterTable
OUTER APPLY(
SELECT TOP 1 SubID FROM Table1
WHERE Table1.MasterID=MasterTable.MasterID
CASE
WHEN
(
SELECT TOP 1 SubID FROM Table2
WHERE Table2.MasterID=MasterTable.MasterID
ORDER BY Date DESC
) Is NULL
THEN Table1.OrderNum=
(
SELECT TOP 1 OrderNum
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
ELSE Table1.SubId=
(
SELECT TOP 1 SubId
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
END
) SubData
答案 0 :(得分:1)
快速重写一次将导致以下结果:
IF ((SELECT TOP 1 SubID FROM Table2 WHERE Table2.MasterID=MasterTable.MasterID ORDER BY Date DESC) IS NULL)
BEGIN
SELECT
MasterID, OtherInfo, SubID
FROM MasterTable
OUTER APPLY(
SELECT TOP 1 SubID FROM Table1
WHERE
Table1.MasterID=MasterTable.MasterID
AND Table1.OrderNum =
(
SELECT TOP 1 OrderNum
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
) SubData
END
ELSE
BEGIN
SELECT
MasterID, OtherInfo, SubID
FROM MasterTable
OUTER APPLY(
SELECT TOP 1 SubID FROM Table1
WHERE
Table1.MasterID=MasterTable.MasterID
AND Table1.SubId=
(
SELECT TOP 1 SubId
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
) SubData
END
但正如你所指出的那样让它看起来很难看,因为你现在在两个地方都有这种复杂性......
我想你也可以用这种方式表达它(未经测试,但这应该将你的复杂逻辑保存在一个地方):
SELECT
MasterID, OtherInfo, SubID
FROM MasterTable
OUTER APPLY(
SELECT TOP 1 SubID FROM Table1
WHERE Table1.MasterID=MasterTable.MasterID
AND
(
(
(
SELECT
TOP 1 SubID
FROM Table2
WHERE Table2.MasterID=MasterTable.MasterID
ORDER BY Date DESC
) IS NULL
AND
Table1.OrderNum =
(
SELECT TOP 1 OrderNum
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
)
OR
(
Table1.SubId =
(
SELECT
TOP 1 SubId
FROM Table2
WHERE Table2.MasterId=MasterTable.MasterId
ORDER BY Date DESC
)
)
)
) SubData
答案 1 :(得分:0)
如果Table1和Table2中的SubID和OrderNum相同,您可以使用嵌套select语句的简单查询:
select m.MasterID, m.OtherInfo, (
select top 1 coalesce(t2.SubID, t2.OrderNum) from Table2 t2
where t2.MasterID = m.MasterID order by date desc
) as SubID
from MasterTable m;