简体   繁体   English

带分组的SQL更新

[英]SQL Update with grouping

Ok i have had a look through some questions on updating with a group by and found sql doesnt do it but i cant figure out how to perform an update on this particular query. 好的,我已经查看了有关通过group by更新的一些问题,发现sql并没有做到这一点,但是我无法弄清楚如何对该特定查询执行更新。

I have a cashbook with a load of transactions on and they match up to a bank statement but the problem is the bank statement is an aggregated value, so i need to group by the amount on the transactions in particular ways and match on these summed values. 我有一本现金簿,上面有很多交易,它们匹配到银行对账单,但是问题是银行对账单是一个汇总值,所以我需要按特定方式对交易金额进行分组,然后对这些汇总值进行匹配。 Once there is a positive match i then need to update each of those rows in that group on the cashbook to be reconciled. 一旦存在正匹配项,我就需要更新要核对的现金簿上该组中的每一行。

What i have done so far is to get the correct grouping and then do an inner join to the bank statment to bring back all the values that match but obviously dont know how to update these rows.... 到目前为止,我所做的是获取正确的分组,然后对银行报表进行内部联接以带回所有匹配的值,但显然不知道如何更新这些行。

Anyone got any ideas? 任何人有任何想法吗?

Thanks 谢谢

You can store your results in a temporary table (CREATE TEMPORARY TABLE in MySQL) and then use it to filter your update. 您可以将结果存储在临时表(MySQL中的CREATE TEMPORARY TABLE)中,然后使用它来过滤更新。

SELECT id, name, firstname INTO #tmp FROM stuff;
UPDATE other SET count='new value' WHERE id IN (SELECT id FROM #tmp);

The Syntax maybe wrong since I don't use MSSQL 语法可能有误,因为我不使用MSSQL

If I understand you correctly, you can determine the users to update using a select query and then just update these. 如果我对您的理解正确,则可以使用选择查询确定要更新的用户,然后仅更新这些用户。 I think the following query does what you intend: 我认为以下查询可以满足您的要求:

with toupdate as (select userid
                  from (select userid, sum(value) as sumvalue
                        from cashbook cb
                        group by userid
                       ) join
                       bankstatement bs
                       on cb.userid = bs.userid 
                  where cb.sumvalue = bs.value
                 )
update cashbook
    set reconciled = 1
from toupdate
where cashbook.userid = toupdaqte.userid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM