我无法克服此错误。我正在使用SQL Server 2017(v14):
无法绑定多部分标识符“ PS_FFC.Date”。不能绑定多部分标识符“ PS_FFC.Date:”。不能绑定多部分标识符“ PS_FFC.Employee ID”。
代码:
SELECT
[Employee ID],
(SELECT SUM(Total) AS Expr1
FROM dbo.PS_FFC
WHERE (PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 1)))
AND (PS_FFC.Date < GETDATE())
GROUP BY PS_FFC.[Employee ID]) AS Current_Month_FFCs,
(SELECT SUM(Total) AS Expr2
FROM dbo.PS_FFC AS PS_FFC_2
WHERE (PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 2)))
AND (PS_FFC.Date < EOMONTH(GETDATE(), - 1))
GROUP BY PS_FFC.[Employee ID]) AS Prior_Month_FFCs
FROM
dbo.PS_FFC AS PS_FFC_1
我要从中提取的表如下:
Employee ID| Date| FFC
Emp000 1/1/2019 1
Emp000 1/2/2019 2
Emp000 12/31/2019 1
Emp001 1/3/2019 1
Emp003 1/20/2019 2
Emp004 2/5/2019 4
我希望结果看起来像这样:
Employee ID| Current_Month_FFCs| Prior_Month_FFCs
Emp000 0 3
Emp001 0 1
Emp003 0 2
Emp004 4 0
答案 0 :(得分:1)
您的第二个子查询对表使用别名PS_FFC_2,而您引用的是PS_FFC。 好处是您不需要子查询,而只需使用CASE表达式仅聚合所需的行即可。
SELECT PS_FFC.[Employee ID],
SUM( CASE WHEN PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 1)) AND PS_FFC.Date < GETDATE()
THEN PS_FFC.Total ELSE 0 END) AS Current_Month_FFCs,
SUM( CASE WHEN PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 2)) AND PS_FFC.Date < DATEADD(DAY, 1, EOMONTH(GETDATE(), - 1))
THEN PS_FFC.Total ELSE 0 END) AS Prior_Month_FFCs
FROM dbo.PS_FFC AS PS_FFC
WHERE PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 2))
AND PS_FFC.Date < GETDATE()
GROUP BY Employee_ID;
答案 1 :(得分:0)
在第二个子查询中,您将PS_FFC
别名为PS_FFC_2
。要解决它的列,请使用别名例如PS_FFC_2.Date
不是原始名称(例如PS_FFC.Date
)。或不要为表添加别名。
答案 2 :(得分:0)
一旦为表加上别名,就必须使用别名。您在第二个子查询中没有这样做:
(SELECT SUM(Total) AS Expr2
FROM dbo.PS_FFC AS PS_FFC_2
WHERE (PS_FFC.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 2))) AND (PS_FFC.Date < EOMONTH(GETDATE(), - 1))
GROUP BY PS_FFC.[Employee ID]) AS Prior_Month_FFCs
应为:
(SELECT SUM(Total) AS Expr2
FROM dbo.PS_FFC AS PS_FFC_2
WHERE (PS_FFC_2.Date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), - 2))) AND (PS_FFC_2.Date < EOMONTH(GETDATE(), - 1))
GROUP BY PS_FFC_2.[Employee ID]) AS Prior_Month_FFCs