希望我描述的方式有意义。我试图在同一列上使用多个Case语句,以在同一行中但在不同字段中输出值。让我们以缺勤计划为例。
就我而言,我正在尝试进行审核以确保为所有员工分配了所需的6种不同的缺勤计划。计划1、2和3每个都有多个可以分配以满足需求的计划。 (例如计划1a /计划2a /计划3a或计划1b /计划2c /计划3a ...)
所有计划都存储在同一张表中,结果所有输出在不同的行上。如果分配了每个计划,我试图输出1行标记,这提供了一个输出,其中一个人有一个计划的6行显示为分配给每行,而其他所有行都没有分配。
SELECT (CASE
WHEN Table1.[Plan] Like ('PlanType1')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan1 Missing'
END) AS [Plan1],
(CASE
WHEN Table1.[Plan] Like ('PlanType2')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan2 Missing'
END) AS [Plan2],
(CASE
WHEN Table1.[Plan] Like ('PlanType3')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan3 Missing'
END) AS [Plan3],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan4%') THEN NULL
ELSE 'Plan4 Missing'
END) AS [Plan4],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan5%') THEN NULL
ELSE 'Plan5 Missing'
END) AS [Plan5],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan6%') THEN NULL
ELSE 'Plan6 Missing'
END) AS [Plan6],
答案 0 :(得分:0)
类似这样的东西:
SELECT max(s.[Plan1]), max(s.[Plan2]), max(s.[Plan3]),max(s.[Plan4]),max(s.[Plan5]),max(s.[Plan6])
from (
SELECT (CASE
WHEN Table1.[Plan] Like ('PlanType1')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan1 Missing'
END) AS [Plan1],
(CASE
WHEN Table1.[Plan] Like ('PlanType2')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan2 Missing'
END) AS [Plan2],
(CASE
WHEN Table1.[Plan] Like ('PlanType3')
AND [enrectype] = 'ABS' THEN NULL
ELSE 'Plan3 Missing'
END) AS [Plan3],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan4%') THEN NULL
ELSE 'Plan4 Missing'
END) AS [Plan4],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan5%') THEN NULL
ELSE 'Plan5 Missing'
END) AS [Plan5],
(CASE
WHEN Table1.[PlanDescrip] like ('%Plan6%') THEN NULL
ELSE 'Plan6 Missing'
END) AS [Plan6],
...) s
如果按某些属性将此信息分组,请按此字段添加最终的group by子句(在查询中不显示)
答案 1 :(得分:0)
这有点痛苦-表达存在的内容比丢失的内容要容易得多。一种方法是case
的两个级别,一个带有计数,一个带有字符串。这是另一种方法
SELECT NULLIF(MIN(CASE WHEN Table1.[Plan] Like 'PlanType1' AND [enrectype] = 'ABS' THEN 'ZZZ' ELSE 'Plan1 Missing'
END), 'ZZZ') AS [Plan1],
NULLIF(MIN(CASE WHEN Table1.[Plan] Like 'PlanType2' AND [enrectype] = 'ABS' THEN 'ZZZ' ELSE 'Plan2 Missing'
END), 'ZZZ') AS [Plan2],
. . .