有2个表格 - DepoSevkDetay
和SatisDetay
。两者都有列 - Miktar
和UrunID
。我需要在Miktar
中DepoSevkDetay
为UrunID
求和,Miktar
等于SatisDetay
中UPDATE
Table_A
SET
Table_A.[Miktar] = (((Table_B.Miktar)/Table_C.c) +
(case when ((Table_B.Miktar) % Table_C.c < Table_C.r) then 1
else 0 end ))
FROM
[Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
INNER JOIN (
SELECT SUM(Miktar)as Miktar, UrunID
FROM tb_SatisDetay
GROUP BY UrunID ) AS Table_B
ON Table_A.[UrunID] = Table_B.[UrunID]
INNER JOIN (
SELECT COUNT([UrunID]) AS c, ROW_NUMBER() OVER (ORDER BY UrunID) r, UrunID as UrunID
FROM tb_DepoSevkDetay
GROUP BY UrunID ) AS Table_C
ON Table_B.[UrunID] = Table_C.[UrunID]
的总和。查询我写的不能处理它。我究竟做错了什么?考虑到两个表中的记录数不相等
input
答案 0 :(得分:0)
我会这样做。首先,我会让Miktar = 0:
UPDATE [Retail].[dbo].[tb_DepoSevkDetay]
SET [Miktar] = 0
然后我会更新所有记录,但首先使用Miktar等于sum(Miktar)/(Count(*))
; with Table_A as (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY UrunID ORDER BY UrunID) as rn,
COUNT(*) OVER (PARTITION BY UrunID) as c
[Retail].[dbo].[tb_DepoSevkDetay])
UPDATE
Table_A
SET
Table_A.[Miktar] = Table_B.Miktar/(Table_A.c)
FROM
Table_A
INNER JOIN (
SELECT SUM(Miktar)as Miktar, UrunID
FROM tb_SatisDetay
GROUP BY UrunID ) AS Table_B
ON Table_A.[UrunID] = Table_B.[UrunID]
WHERE Table_A.c > 0 and Table_A.rn > 1
然后我会更新剩下的[Miktar],就像这样:
UPDATE
Table_A
SET
Table_A.[Miktar] = Table_B.Miktar - Table_C.Miktar
FROM
[Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
INNER JOIN (
SELECT SUM(Miktar)as Miktar, UrunID
FROM tb_SatisDetay
GROUP BY UrunID ) AS Table_B
ON Table_A.[UrunID] = Table_B.[UrunID]
INNER JOIN (
SELECT SUM(Miktar)as Miktar, UrunID
FROM [Retail].[dbo].[tb_DepoSevkDetay]
GROUP BY UrunID ) AS Table_C
ON Table_A.[UrunID] = Table_C.[UrunID]
WHERE Table_A.[Miktar] = 0
希望,这很有意义
答案 1 :(得分:0)
你的要求不是很清楚。
用一个例子解释
update dd
set Miktar=sd.Miktar
DepoSevkDetay DD
inner join
(select UrunID, sum(Miktar) Miktar
from SatisDetay
group by UrunID)SD
on dd.UrunID=sd.UrunID