我在SQL Server Management Studio 2012中有一个UPDATE查询,它没有给我预期的结果。我相信这是因为我必须将IJDATE字段添加到SELECT和GROUP BY,因此它不能正确求和。我正在尝试更新每个供应商的当前月份/年份。有没有更好的方法来编写此UPDATE查询?
UPDATE S
SET S.PurchaseDlr = I.PurchaseDlr
FROM (SELECT
IJVEND,
IJDATE,
SUM(IJQTY * IJCOST) AS PurchaseDlr
FROM
dbo.S2K_IJ
WHERE
IJTYPE IN ('I','ID')
GROUP BY
IJVEND,
IJDATE) I
INNER JOIN PurchaseDollars S on I.IJVEND = S.Vendor AND S.MonthNum = MONTH(I.IJDATE) AND S.Year = YEAR(I.IJDATE)
答案 0 :(得分:1)
您按日期分组,但看起来您希望按月和年分组:
UPDATE S
SET S.PurchaseDlr = I.PurchaseDlr
FROM (SELECT
IJVEND,
MONTH(IJDATE) AS Month,
YEAR(IJDATE) AS Year,
SUM(IJQTY * IJCOST) AS PurchaseDlr
FROM
dbo.S2K_IJ
WHERE
IJTYPE IN ('I','ID')
GROUP BY
IJVEND,
MONTH(IJDATE),
YEAR(IJDATE)) I
INNER JOIN PurchaseDollars S
ON I.IJVEND = S.Vendor
AND S.MonthNum = I.Month
AND S.Year = I.Year