我有一个使用CTE定义员工部门的查询。
当查询优化器选择哈希匹配联接时,CTE溢出到tempdb。
如果有帮助,我的代码如下:
;WITH cte_Staff_Departments
AS (
SELECT DISTINCT
[stf].[contact_id]
, CASE
WHEN [stf].[department] NOT IN('HR', 'SALES', 'IT')
THEN [dpt].[department]
ELSE [stf].[department]
END AS [Department]
FROM [dbo].[staff] AS [stf]
LEFT OUTER JOIN [dbo].[departments] AS [dpt] ON [stf].[contact_id] = [dpt].[contact_id]
WHERE ([stf].[ownership_group] in ('COR','SLE')
OR [dpt].[ownership_group] in ('COR','SLE')
)
select contact_id, department from cte_Staff_Departments
谢谢 LS23
答案 0 :(得分:0)
@ lindsayScott23,我只是建议。请不要把我打倒。我实际上将取消CTE,并使用子查询编写查询。像这样:
SELECT contact_id, department
FROM (
SELECT
[stf].[contact_id],
CASE
WHEN [stf].[department] NOT IN('HR', 'SALES', 'IT')
THEN [dpt].[department]
ELSE [stf].[department]
END AS [Department]
FROM [dbo].[staff] AS [stf]
LEFT JOIN [dbo].[departments] AS [dpt]
ON [stf].[contact_id] = [dpt].[contact_id]
AND (
[stf].[ownership_group] in ('COR','SLE')
OR
[dpt].[ownership_group] in ('COR','SLE')
)
) CSD
GROUP BY
contact_id, department