MyTable:
item_name Qty item_area
Belts 2 India
Shoes 20 US
T-Shirt 10 India
T-Shirt 12 US
T-Shirt 25 US
我通过按查询选择组来获取
SELECT item_name, Sum(item_qty) as Qty, item_area
FROM dbo.item_stocks
group by item_area, item_name
我的输出如下:
item_name Qty item_area
Belts 2 India
Shoes 20 US
T-Shirt 10 India
T-Shirt 37 US
现在我需要减去和更新。我该怎么做? 例如。我想减去5个T恤,它会在我的桌子上更新吗?
T-shit = 37-5 = 32
如何在mytable中更新?
答案 0 :(得分:2)
您可以尝试使用ROW_NUMBER
窗口函数选择要减去的任何一行。
;WITH CTE AS (
SELECT *,ROW_NUMBER() over(PARTITION BY item_name,item_area order by Qty desc)rn
FROM item_stocks
)
update CTE
set Qty = Qty - 5
where rn = 1 and item_name = 'T-Shirt' and item_area = 'US'
SELECT item_name, Sum(Qty) as Qty, item_area
FROM item_stocks
group by item_area, item_name
答案 1 :(得分:2)
只需添加一个表示输入/输出的列,例如INOUT
不更新行,只需为股票销售添加新行即可。
在这里
INOUT = 1表示IN,2表示OUT
表结构类似
item_name Qty item_area INOUT
Belts 2 India 1
Shoes 20 US 1
T-Shirt 10 India 1
T-Shirt 12 US 1
T-Shirt 25 US 1
T-Shirt 5 US 2
现在您的查询就是这样
SELECT item_name,
Sum(case when INOUT = 1 then item_qty else (0-item_qty) end) as Qty,
item_area
FROM dbo.item_stocks
group by item_area, item_name