我正在尝试使用Case语句来查找表格,如果表格显示了舞台06和舞台11,那么如果仅显示舞台06则将其视为修改后,则不会修改。
我目前的代码是:
DECLARE
@DATE1 DATETIME = '04/01/2017',
@DATE2 DATETIME = '04/30/2017',
@RAISEDBY VARCHAR (10) = 'CAROLIND'
SELECT DISTINCT
J.[RAISED-BY],
J.[JOB-NO],
J.[JOB-STATUS],
J.[DATE-LOGGED],
J.[CURRENT-STAGE-CODE],
J.[ORIG-LOGGED-VALUE] AS "LOGGED-VALUE",
J.[TOTAL-VALUE],
J.[SHORT-DESCRIPTION],
J.[CONTRACTOR],
C.[DESCRIPTION],
CASE
WHEN SH.[STAGE-CODE] = '06' AND SH.[STAGE-CODE] = '11' THEN 'YES'
ELSE 'NO'
END AS "AMENDED"
FROM
DBO.[JOB] AS J
LEFT OUTER JOIN
DBO.[CONT] as C ON C.CONTRACTOR = J.CONTRACTOR
LEFT OUTER JOIN
DBO.[JOB-STAGE-HISTORY] AS SH ON SH.[JOB-NO] = J.[JOB-NO]
WHERE
J.[DATE-LOGGED] BETWEEN @DATE1 AND @DATE2
AND
J.[RAISED-BY] = @RAISEDBY
AND
SH.[JOB-NO] = 'W0423540'
ORDER BY
J.[RAISED-BY],
J.[JOB-NO]
当查询为'YES'时,此查询当前返回'NO',因为在Job Stage History表中有一行06和11。
由于
查询结果
工作阶段历史表
答案 0 :(得分:0)
您的CASE
正在检查记录中的单个字段是否等于两个不同的值,这些值始终为false。你想要的是检查JOB-STAGE-HISTORY
表中是否存在两个不同的行( 06 行, 11 行)。尝试用{:
CASE
case when (select count(distinct j.[STAGE-CODE])
from [JOB-STAGE-HISTORY] j
where j.[JOB-NO] = sh.[JOB-NO]
and j.[STAGE-CODE] in ('06','11')) = 2
then 'YES' else 'NO' end AMENDED
答案 1 :(得分:0)
不确定以下内容是否会获取结果。
修改/添加连接条件,如下所示。
LEFT OUTER JOIN
DBO.[JOB-STAGE-HISTORY] AS SH ON SH.[JOB-NO] = J.[JOB-NO]
and sh.[STAGE-CODE] = 06
left outer join
dbo.[JOB-STAGE-HISTORY] AS SH1 on SH1.[JOB-NO] = SH.[JOB-NO]
and SH1.[STAGE-CODE] = 11
添加连接条件后,更改case语句如下。
CASE
WHEN SH1.[STAGE-CODE] is null then 'No' else 'Yes' end.
答案是基于您对问题的假设。
答案 2 :(得分:0)
由于涉及到两者,所提供的答案都很有效。我花了一些时间来研究这个挑战,并相信这可能是另一种解决方法:
SELECT DISTINCT
J.[RAISED-BY],
J.[JOB-NO],
J.[JOB-STATUS],
J.[DATE-LOGGED],
J.[CURRENT-STAGE-CODE],
J.[ORIG-LOGGED-VALUE] AS "LOGGED-VALUE",
J.[TOTAL-VALUE],
J.[SHORT-DESCRIPTION],
J.[CONTRACTOR],
C.[DESCRIPTION],
SH.[JOB-AMENDED]
FROM
DBO.[JOB] AS J
LEFT OUTER JOIN
DBO.[CONT] as C ON C.CONTRACTOR = J.CONTRACTOR
RIGHT OUTER JOIN
(SELECT
[JOB-NO],
CASE WHEN MAX([STAGE-CODE]) = ('11') THEN 'YES' ELSE 'NO' END AS "JOB-AMENDED"
FROM
DBO.[JOB-STAGE-HISTORY]
WHERE [STAGE-CODE] IN ('06','11')
GROUP BY [JOB-NO]) AS SH ON J.[JOB-NO] = SH.[JOB-NO]
WHERE
J.[DATE-LOGGED] BETWEEN @DATE1 AND @DATE2
AND
J.[RAISED-BY] = @RAISEDBY
它肯定会提供所需的结果以及提供的其他答案。