SQL Server 子查询返回了多个值,当子查询跟在=、!=后面或子查询用作表达式时,不允许出现这种情况

t8e9dugd  于 2023-02-03  发布在  其他
关注(0)|答案(3)|浏览(239)

我需要使用查询结果更新tableA的total字段

select SUM(amt)  from SALES group by DATE,RNAME

我试过这样

UPDATE tableA
SET Total = (
        SELECT Sum(billamt)
        FROM SALES
        GROUP BY DATE
            ,RNAME
        )

显示以下错误
子查询返回了多个值。当子查询跟在=、!=、〈、〈=、〉、〉=后面或子查询用作表达式时,不允许出现这种情况。

txu3uszq

txu3uszq1#

查询:

select sum(billamt) from SALES group by DATE,RNAME

返回按DATE,RNAME分组的billamtsum
如果有多个DATERNAME唯一值,则返回值是一个表(而不是一个字段)。
可以单独运行此查询并检查返回值。
如错误所述,不能为一个字段设置多个值。

nvbavucw

nvbavucw2#

尝试以下内容:

update A
set Total = B.Total
From tableA  A
Inner Join (select DATE,RNAME,sum(billamt) Total from SALES group by DATE,RNAME) B
On A.Date = B.Date and A.RName = B.RNAme
rdlzhqv9

rdlzhqv93#

由于在上面的问题中表的结构不清楚,我假设tableA有列Total、Date和RName

update tableA set tableA.total = 
a.total from (select SUM(amt) as total, date, rname from SALES group by DATE,RNAME) as a
where a.date = tableA.date and tableA.rname = a.rname

--编辑“销售表中Rname可以为空的情况”使用

update tableA set tableA.total = a.total
from (select SUM(amt) as total, date, rname from #t1 group by DATE,RNAME) as a
where a.date = tableA.date and tableA.rname = a.rname
OR (a.date = tableA.date AND tableA.rname IS NULL and a.rname IS NULL)

--进一步阐述

CREATE TABLE #t1 (amt decimal(18,2), [date] date, rname varchar(50))
INSERT INTO #t1
SELECT 1.9, GETDATE() - 1, NULL
UNION ALL
SELECT 1.9, GETDATE() - 1, NULL
UNION ALL
SELECT 8.9, GETDATE() - 1, NULL
UNION ALL
SELECT 8.9, GETDATE(), NULL
UNION ALL
SELECT 2.9, GETDATE() - 1, 'N1'
UNION ALL
SELECT 2.8, GETDATE() - 1, 'N1'

CREATE TABLE #t2 (total decimal(18,2), [date] date, rname varchar(50))
INSERT INTO #t2
SELECT 0, GETDATE() - 1, NULL
UNION ALL
SELECT 0, GETDATE() - 1, 'N1'

update #t2 set #t2.total = a.total
from (select SUM(amt) as total, date, rname from #t1 group by DATE,RNAME) as a
where a.date = #t2.date and #t2.rname = a.rname
OR (a.date = #t2.date AND #t2.rname IS NULL and a.rname IS NULL)

SELECT * FROM #t2

我希望现在一切都清楚了

相关问题