好,所以我有一个类似
的查询SELECT
CASE WHEN EXISTS(SELECT NULL
FROM B
WHERE B.LENGTH = A.LENGTH + 10)
THEN 'Yes'
ELSE 'No'
END AS Result1,
CASE WHEN EXISTS(SELECT NULL
FROM B
WHERE B.LENGTH = A.LENGTH - 10)
THEN 'Yes'
ELSE 'No'
END AS Result2,
CASE WHEN EXISTS(SELECT NULL
FROM B
WHERE B.LENGTH = A.LENGTH)
THEN 'Yes'
ELSE 'No'
END AS Result3
FROM A
如您所见,这3个EXIST查询几乎相同,并且几乎没有区别(我希望)可以作为参数传递。
我试图创建一个TVF,但是当我返回SELECT NULL...
时,它会失败,但是如果我使用SELECT *
,它会起作用。我担心的是,我不需要要检查的值是否仅存在而已。
我的问题是重构此代码的最佳方法是什么,这样就不会那么重复了?
答案 0 :(得分:2)
您可以使用条件聚合来生成每行包含三列的一个查询:
SELECT CASE WHEN CA.C1 > 0 THEN 'Yes' ELSE 'No' END
, CASE WHEN CA.C2 > 0 THEN 'Yes' ELSE 'No' END
, CASE WHEN CA.C3 > 0 THEN 'Yes' ELSE 'No' END
FROM A
CROSS APPLY (
SELECT COUNT(CASE WHEN B.LENGTH = A.LENGTH + 10 THEN 1 END)
, COUNT(CASE WHEN B.LENGTH = A.LENGTH - 10 THEN 1 END)
, COUNT(CASE WHEN B.LENGTH = A.LENGTH THEN 1 END)
FROM B
WHERE B.LENGTH IN (A.LENGTH + 10, A.LENGTH - 10, A.LENGTH)
) AS CA(C1, C2, C3)
答案 1 :(得分:0)
您可以执行以下操作:
SELECT A.Length,
CASE COUNT(CASE A.[LENGTH] WHEN B.[LENGTH] - 10 THEN 1 END)WHEN 0 THEN 'No' ELSE 'Yes' END AS result1,
CASE COUNT(CASE A.[LENGTH] WHEN B.[LENGTH] + 10 THEN 1 END)WHEN 0 THEN 'No' ELSE 'Yes' END AS result2,
CASE COUNT(CASE A.[LENGTH] WHEN B.[LENGTH] THEN 1 END)WHEN 0 THEN 'No' ELSE 'Yes' END AS result3
FROM A
CROSS JOIN B
GROUP BY A.Length;
这可以节省对表B
的3次扫描,但是您仍然需要某种重复性逻辑。