table 包含产品的销售额和数量 - 添加计算产品的列
table with sales and quantity of products - add column that count the products
我有这个table:
我想添加 column:count - 我可以看到每种产品的销售额,如下所示:
我这样试:
update #t
set quantity = (select count(*) from #t group by product)
不好,因为它 return 超过 1 个值
您可以使用window函数:
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;
使用window函数:
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
使用window函数:
update #t
set quantity = new_quantity
from (select t.*, count(*) over (partition by product) as new_quantity
from #t t
) t;
您可能应该在 创建 临时 table 时执行此操作,但之后您也可以更新该值。
我有这个table:
我想添加 column:count - 我可以看到每种产品的销售额,如下所示:
我这样试:
update #t
set quantity = (select count(*) from #t group by product)
不好,因为它 return 超过 1 个值
您可以使用window函数:
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;
使用window函数:
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
使用window函数:
update #t
set quantity = new_quantity
from (select t.*, count(*) over (partition by product) as new_quantity
from #t t
) t;
您可能应该在 创建 临时 table 时执行此操作,但之后您也可以更新该值。