【问题标题】:table with sales and quantity of products - add column that count the products包含产品销售额和数量的表 - 添加计算产品的列
【发布时间】:2020-06-10 11:46:03
【问题描述】:
我有这张桌子:
我想添加 column:count - 我可以查看每个产品的销售额,如下所示:
我尝试这样:
update #t
set quantity = (select count(*) from #t group by product)
这不好,因为它返回的值超过 1 个
【问题讨论】:
标签:
sql
sql-server
count
aggregation
【解决方案1】:
您可以使用窗口功能:
sum(quantity) over (partition by product)
或者你可以关联你的子查询:
update t1
set t1.quantity = (select sum(t.quantity)
from #t as t
where t.product = t1.product
)
from #t t1;
【解决方案2】:
使用窗口函数:
select
t.*,
sum(quantity) over(partition by product) cnt
from mytable t
正如 jarlh 所建议的,比更新更好的想法是创建一个视图,因此您不必担心维护派生列的完整性:
create view myview
select
t.*,
sum(quantity) over(partition by product) cnt
from mytable t
【解决方案3】:
使用窗口函数:
update #t
set quantity = new_quantity
from (select t.*, count(*) over (partition by product) as new_quantity
from #t t
) t;
您可能应该在创建临时表时执行此操作,但之后您也可以更新该值。