我正在进行一个长查询,这是其中的一部分:
SELECT '3' AS RowType
,DTH.EnteredBy AS Person
,COALESCE(PDT.[Name], APP.AppName) AS Project
,(
CASE WHEN (
STY.KanBanProductId IS NOT NULL
AND STY.SprintId IS NULL
) THEN 'Kanban' WHEN (
STY.KanBanProductId IS NULL
AND STY.SprintId IS NOT NULL
) THEN 'Sprint' ELSE SCY.Catagory END
) AS ProjectType
,dbo.primaryTheme(STY.[Number], ???) AS Theme
哪里???是的,我遇到了问题。
我需要传递上一列的结果,即:
CASE WHEN (
STY.KanBanProductId IS NOT NULL
AND STY.SprintId IS NULL
) THEN 'Kanban' WHEN (
STY.KanBanProductId IS NULL
AND STY.SprintId IS NOT NULL
) THEN 'Sprint' ELSE SCY.Catagory END
)
实现这一目标的最佳方法是什么?
答案 0 :(得分:1)
您可以重复查询,只执行一次,或者您可以使用子查询/ CTE:
WITH CTE AS
(
SELECT '3' AS RowType
,DTH.EnteredBy AS Person
,COALESCE(PDT.[Name], APP.AppName) AS Project
,(
CASE WHEN (
STY.KanBanProductId IS NOT NULL
AND STY.SprintId IS NULL
) THEN 'Kanban' WHEN (
STY.KanBanProductId IS NULL
AND STY.SprintId IS NOT NULL
) THEN 'Sprint' ELSE SCY.Catagory END
) AS ProjectType
FROM dbo.TableName
)
SELECT *, Theme = dbo.primaryTheme(Number, ProjectType)
FROM CTE
答案 1 :(得分:1)
您可以使用“Cross Apply”或CTE(Common Table Expression)来执行此操作。我更喜欢Cross Apply,所以这里有一个例子:
SELECT '3' AS RowType
,DTH.EnteredBy AS Person
,COALESCE(PDT.[Name], APP.AppName) AS Project
,CAResult.ProjectType
,dbo.primaryTheme(STY.[Number], CAResult.ProjectType) AS Theme
FROM [SomeTable]
CROSS APPLY (SELECT CASE WHEN (
KanBanProductId IS NOT NULL
AND SprintId IS NULL
) THEN 'Kanban' WHEN (
KanBanProductId IS NULL
AND SprintId IS NOT NULL
) THEN 'Sprint' ELSE Catagory END
) AS ProjectType) as CAResult
答案 2 :(得分:0)
CTE可能是你最好的选择。
WITH CTE
AS
(
SELECT '3' AS RowType
,DTH.EnteredBy AS Person
,COALESCE(PDT.[Name], APP.AppName) AS Project
,(
CASE WHEN (
STY.KanBanProductId IS NOT NULL
AND STY.SprintId IS NULL
) THEN 'Kanban' WHEN (
STY.KanBanProductId IS NULL
AND STY.SprintId IS NOT NULL
) THEN 'Sprint' ELSE SCY.Catagory END
) AS ProjectType
FROM Table STY
)
select c.*, dbo.primaryTheme(STY.[Number], c.ProjectType) from CTE as c join Table STY on t.ID = c.id