我需要更新tableA的总计字段 与查询的结果 按DATE,RNAME
从SALES组中选择SUM(amt)我试过这个
更新表设置总计=(从DATE,RNAME中选择SALES组的总和(billamt)
显示错误 子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
答案 0 :(得分:4)
查询:
select sum(billamt) from SALES group by DATE,RNAME
返回sum
的{{1}},按billamt
分组。
如果您有多个DATE,RNAME
或DATE
个唯一值,则返回的值是一个表(而不是一个字段)。
您可以单独运行此查询并检查返回的值。
如错误所述,您不能为字段设置多个值。
答案 1 :(得分:2)
尝试类似:
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
答案 2 :(得分:2)
由于表结构在上述问题中不明确,我假设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
我希望现在明白