我正在尝试编写一个可以定义变量的视图。其中之一是“StateCd”变量。在我的查询中,我需要过滤到我在变量中定义的状态以及我在第二个WITH
语句中定义的所有其他状态。我如何编写一个代码来选择第二个WITH
语句中的所有状态,除了我在“StateCd”中定义的状态
WITH MyVars (StateCd, DateDay, CompanyCd, LineCd) AS
(
SELECT
'SD' AS StateCd,
'2017-11-30' AS IssueDate,
'010' AS CompanyCd,
'010' AS LineCd
), MyStates (CO, IA, KS, MO, MT, NE, ND, SD, WY) AS
(
SELECT
'CO' AS CO,
'IA' AS IA,
'KS' AS KS,
'MO' AS MO,
'MT' AS MT,
'NE' AS NE,
'ND' AS ND,
'SD' AS SD,
'WY' AS WY
)
答案 0 :(得分:1)
您的状态列表应该是数据而不是模式,这意味着您应该以不同方式构建第二个CTE。然后使用OUTER JOIN。
WITH MyVars (StateCd, DateDay, CompanyCd, LineCd)
AS (
SELECT
'SD' AS StateCd,
'2017-11-30' AS IssueDate,
'010' AS CompanyCd,
'010' AS LineCd
),
MyStates ([State])
AS (
SELECT 'CO' AS [State] UNION
SELECT 'IA' UNION
SELECT 'KS' UNION
SELECT 'MO' UNION
SELECT 'MT' UNION
SELECT 'NE' UNION
SELECT 'ND' UNION
SELECT 'SD' UNION
SELECT 'WY'
)
SELECT MyStates.[State]
FROM MyStates
LEFT JOIN MyVars ON MyVars.StateCd = MyStates.[State]
WHERE MyVars.StateCd IS NULL;