我有一个表(tran),其中包含以下值:
Set Type Acc Type Tran Value
---- ----- ---------- ---------- ------------------- -----------
1 BS 87411 CCHQ Other Transactions -200
1 BS 87411 RECPT Other Transactions 200
1 BS 87411 CCHQ Other Transactions -200
1 BS 87411 RECPT Other Transactions 200
如何更新此表以按类型订购商品。我应该提到这段代码是SP的一部分,我不能使用select,因为我不希望通过更新表来输出。
我尝试过类似的事情:
update a
set Value = sum(Value)
from tran a
group by TranType
但这不起作用,显示错误“组附近的语法不正确”
答案 0 :(得分:0)
你不能这样做。试试这个:
update a
set a.Value = t.Total
from tran a
INNER JOIN
(
SELECT TranType, SUM(Value) Total
FROM tran
GROUP BY TranType
) AS t ON a.TranType = t.TranType
答案 1 :(得分:0)
更新a 设定值=总和(值) 来自tran a 由Tran分组,[缺少空白字符]类型
答案 2 :(得分:0)
在SQL Server中,一种很好的方法是使用可更新的CTE和窗口函数:
with toupdate as (
select t.*, sum(value) over (partition by trantype) as newvalue
from tran
)
update toupdate
set vaule = newvalue;
也就是说,用总和覆盖原始数据似乎很奇怪。你不应该把它放在另一个专栏或另一个表中吗?
答案 3 :(得分:0)
根据定义,SQL中表的“顺序”不在存储中。
如果请求SQL语句中没有'order by'子句,结果的顺序可能是随机的(或由数据库首选的提取例程给出)。
如果存在'order by'子句,结果将按该子句进行排序。
答案 4 :(得分:0)
这是你可以做的事情之一,我担心没有离开DELETE语句..因为你将无法通过拥有一个总和值的唯一行来覆盖现有数据删除它。
BEGIN TRANSACTION
SELECT ROW_NUMBER() OVER (ORDER BY Type2) AS UniqueID, * --- Create Unique ID if you don't already have one.
INTO #tmpTransactionTypes
FROM dbo.TransactionTypes_Test;
UPDATE A
SET A.Value = B.Total
FROM #tmpTransactionTypes AS A
INNER JOIN (
SELECT Type2, SUM(Value) AS Total
FROM #tmpTransactionTypes
GROUP BY Type2) AS B ON A.Type2 = B.Type2;
DECLARE @FirstValue INT = 1
DECLARE @LastValue INT = (SELECT MAX(UniqueID) FROM #tmpTransactionTypes)
WHILE @FirstValue <= @LastValue
BEGIN
DELETE
FROM #tmpTransactionTypes
WHERE UniqueId = @FirstValue;
SET @FirstValue = @FirstValue +2
END
SELECT *
FROM #tmpTransactionTypes;
-- COMMIT TRANSACTION
ROLLBACK TRANSACTION
结果:
UniqueID Set Type1 Acc Type2 Tran Value
2 1 BS 87411 CCHQ Other Transactions -400.00
4 1 BS 87411 RECPT Other Transactions 400.00