当我运行此代码时
UPDATE #YesterdayAssignments
SET ThisWeek = (
SELECT COUNT(*)
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A
ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S
ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
GROUP BY HHID
)
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A
ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S
ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
AND HHID = U.HHID
我收到了错误;
Msg 512, Level 16, State 1, Line 1
子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。 声明已经终止。
我需要更新一个包含多个值的表。有什么想法吗?
答案 0 :(得分:0)
我认为查询没有按照您的想法进行。试试这个(徒手):
WITH data (Total, HHID) AS
(
SELECT COUNT(*),
HHID
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
GROUP BY HHID
)
UPDATE U
SET ThisWeek = Total
FROM #YesterdayAssignments U
INNER JOIN data D ON D.HHID = U.HHID;
你拥有它的方式,你正在对HHID进行分组,哪个潜在的返回多个计数(当有多个HHID时)。所以实际上,您正在尝试:ThisWeek = val1, val2, ..., valN
。