SQL Server查询(是否按更新分组?)
我有以下表格要处理。(只是一个示例) theadSQL Server查询(是否按更新分组?),sql,sql-server,Sql,Sql Server,我有以下表格要处理。(只是一个示例) thead id date ------------------ 2399 01/01/2017 2400 18/07/2017 2300 11/11/2016 ... t股票 id product_id type stockq result -------------------------------------------- 2399 0000001 1 5
id date
------------------
2399 01/01/2017
2400 18/07/2017
2300 11/11/2016
...
t股票
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
每个产品标识有2个值,类型1和类型2。thead保存id和日期
我需要更新结果,其中stockq类型对于每组产品id为1,其中tproducts.id的日期为“2017年1月1日”
所以它应该以这样的方式结束:
t存货:
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
我尝试了下面的查询,但它在子查询错误上显示了一个以上的值
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'
任何想法都将不胜感激
提前谢谢 我将使用可更新的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;
请注意,我将日期更改为标准格式,并删除了类型周围的单引号。这假设列的类型分别为date
/datetime
和number
您也可以遵循您的推理,但使用相关子查询:
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';
tstocks.type='1'15和17来自哪里?AD和tstocks的表结构是什么?主键是什么?@Amit谢谢,只是输入错误:p@GordonLinoff这是两个stockq值相加的结果。非常感谢大家。工作得很有魅力。