[英]SQL Server query (update grouping by?)
I got the following tables to work with.(Just a sample) 我得到了下面的表格。(只是一个样本)
thead THEAD
id date
------------------
2399 01/01/2017
2400 18/07/2017
2300 11/11/2016
...
tstocks tstocks
id product_id type stockq result
--------------------------------------------
2399 0000001 1 5
2399 0000001 2 10
2399 0000002 1 15
2399 0000002 2 2
2400 0000001 1 4
2400 0000001 2 6
2300 0000003 1 0
2300 0000003 2 5
Each product_id has 2 values, type 1 and type2. 每个product_id都有2个值,类型1和类型2。 thead holds the id and the date. thead持有id和日期。
I need to update result, where stockq type is 1 for each group of product_id, where the date of tproducts.id is '01/01/2017' 我需要更新结果,其中stockq类型为每组product_id为1,其中tproducts.id的日期为'01 / 01/2017'
So it should end up with something like this: 所以最终应该是这样的:
tstocks : tstocks :
id product_id type stockq result
--------------------------------------------
2399 0000001 1 5 15
2399 0000001 2 10
2399 0000002 1 15 17
2399 0000002 2 2
2400 0000001 1 4
2400 0000001 2 6
2300 0000003 1 0
2300 0000003 2 5
I tried with the following query but it says with an more than one value on the subquery error. 我尝试使用以下查询但它在子查询错误上使用了多个值。
update tstocks
set result = (select sum(stockq)
from tstocks
group by tstocks.product_id)
from tstocks
inner join thead ON tstocks.id = thead.id
where tstocks.type = '1' and thead.date = '01/01/2017'
Any ideas would be appreciated. 任何想法,将不胜感激。
Thanks in advance. 提前致谢。
I would use an updatable CTE and window functions: 我会使用可更新的CTE和窗口函数:
with toupdate as (
select s.*, sum(stockq) over (partition by id, product_id) as new_result
from tstocks
)
update toupdate
set result = new_result
from toupdate join
thead
on toupdate.id = thead.id
where thead.date = '2017-01-01' and toupdate.type = 1;
Note that I changed the date to a standard format and dropped the single quotes around the type. 请注意,我将日期更改为标准格式,并删除了类型周围的单引号。 This assumes the columns have the types of date
/ datetime
and number respectively. 这假设列分别具有date
/ datetime
和数字的类型。
You can also follow your reasoning, but with a correlated subquery: 您也可以按照您的推理,但使用相关的子查询:
update s
set result = (select sum(s2.stockq)
from tstocks s2
where s2.product_id = s.product_id an s2.id = s.id
)
from tstocks s inner join
thead h
on s.id = h.id
where s.stockq = 1 and h.date = '2017-01-01';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.