1

当我运行这段代码

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 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。该语句已终止。

我需要更新具有多个值的表。有任何想法吗?

4

1 回答 1

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 可能会返回多个计数(当有多个 HHID 时)。因此,实际上,您正在尝试执行以下操作:ThisWeek = val1, val2, ..., valN.

于 2013-09-06T17:06:43.583 回答