我有一个库存表,我想要GROUP BY
不同批次的相同mfgpn,所以我在数量上使用SUM()
函数来组合相似的记录。我想尝试将最后一个MANUFACTURER记录在该组中,因为它可能是最新/最准确的,但我似乎无法将MANUFACTURER字段转到GROUP最后一个MANUFACTURER下的所有常用部件号,所以我仍然有一个结果中的一堆重复记录。
我目前有以下SELECT查询:
SELECT SUM([QTY]) AS QTY
,[MFGPN]
, (SELECT TOP 1 Manufacturer FROM [post].[dbo].[BF-prefix] B2 WHERE B2.MFGPN=MIN(B.mfgpn)) AS MANUFACTURER
FROM [post].[dbo].[BF-prefix] B
GROUP BY mfgpn, MANUFACTURER
ORDER BY MFGPN ASC
我在SQL Server 2008上运行,如果这有任何区别。
答案 0 :(得分:3)
您可以使用窗口功能来实现您的需求:
;WITH T AS
( SELECT MFGPN,
Manufacturer,
SUM(Qty) OVER(PARTITION BY MFGPN) AS Qty,
ROW_NUMBER() OVER(PARTITION BY MFGPN ORDER BY Manufacturer) AS RowNumber
FROM [Post].[dbo].[BF-prefix]
)
SELECT *
FROM T
WHERE RowNumber = 1
我只是不确定你是如何定义“最后一个制造商”我假设你有一个日期字段,所以你可能需要更改此行中的order by子句
ROW_NUMBER() OVER(PARTITION BY MFGPN ORDER BY Manufacturer) AS RowNumber