如果我单独为两个日期运行select语句,它将返回正确的日期,但是当它包含在代码中时它不会。我需要一些帮助。
SELECT r.[Holding Co],
r.[Reference Order No],
r.Reg,
r.SL,
r.[Order Date],
CASE WHEN [Type]<>'Recovery'
AND [Status]<>'Inter'
AND [Status]<>'Cancelled'
AND [Order Date]<[Date Order]
AND [CICD Actual] IS NULL
OR [CICD Actual]>[Date Outstanding]
THEN 1
ELSE 0 End AS [Outstanding],
--CASE WHEN /* many more calculated fields and cases redacted for brevity ... */
Month([Date Outstanding]) AS [Month],
Year([Date Outstanding]) AS [Year],
CAST(FORMAT(GETDATE(), 'yyyy-MM-01') as Date) AS [Date Order],
DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) AS [Date Outstanding]
FROM unisat.Register AS r;
错误:消息207,级别16,状态1,行3无效的列名称&#39;日期 为了&#39 ;.消息207,级别16,状态1,行4无效的列名称&#39;日期 优秀&#39;
答案 0 :(得分:1)
[日期未完成]是在SELECT列表中引入的,您不能在同一个选择列表中使用它作为其他内容的基础。
我建议将此计算(以及[日期顺序])重构为CTE,然后您可以在外部选择中使用它,如下所示:
;with x as (
SELECT r.[Holding Co],
r.[Reference Order No],
r.Reg,
r.SL,
r.[Order Date],
r.[Type] ,
r.[Status],
r.[CICD Actual],
CAST(FORMAT(GETDATE(), 'yyyy-MM-01') as Date) AS [Date Order],
DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) AS [Date Outstanding]
FROM unisat.Register AS r
)
SELECT x.[Holding Co],
x.[Reference Order No],
x.Reg,
x.SL,
x.[Order Date],
CASE WHEN x.[Type]<>'Recovery'
AND x.[Status]<>'Inter'
AND x.[Status]<>'Cancelled'
AND x.[Order Date]<x.[Date Order]
AND x.[CICD Actual] IS NULL
OR x.[CICD Actual]>x.[Date Outstanding]
THEN 1
ELSE 0 End AS [Outstanding],
CASE WHEN /* many more calculated fields and cases redacted for brevity ... */
Month(x.[Date Outstanding]) AS [Month],
Year(x.[Date Outstanding]) AS [Year],
x.[Date Order],
x.[Date Outstanding]
from x;