stock
列表示零售商当前样式的当前库存数量。包含stock
列的原因是为了避免进行报告联接。 (该表仅用于报告)
我想查询表格以获取当前库存的商品(按样式编号(在各个零售商之间)分组)。喜欢:
select stylenumber,sum(sold) as sold,Max(stock) as stockcount
from MGTest
我希望获得样式编号,总销售量,最新库存总计:
但是使用... Max(Stock),我得到10,而(Sum),我得到25 .... 我也尝试过over(partition .....),也没有任何运气...
我该如何解决?
答案 0 :(得分:2)
我将使用窗口函数来回答这个问题:
SELECT Stylenumber, Date, TotalStock
FROM (SELECT M.Stylenumber, M.Date, SUM(M.Stock) as TotalStock,
ROW_NUMBER() OVER (PARTITION BY M.Stylenumber ORDER BY M.Date DESC) as seqnum
FROM MGTest M
GROUP BY M.Stylenumber, M.Date
) m
WHERE seqnum = 1;
答案 1 :(得分:1)
该查询有些棘手,因为您需要Sold
列的累计总数,但只需要最近日期的Stock
列的总数。我实际上并没有尝试运行它,但是下面的查询应该可以工作。但是,由于架构的形状,这并不是世界上性能最高的查询,因为它会多次扫描表以将所有数据连接在一起:
SELECT MDate.Stylenumber, MDate.TotalSold, MStock.TotalStock
FROM (SELECT M.Stylenumber, MAX(M.Date) MostRecentDate, SUM(M.Sold) TotalSold
FROM [MGTest] M
GROUP BY M.Stylenumber) MDate
INNER JOIN (SELECT M.Stylenumber, M.Date, SUM(M.Stock) TotalStock
FROM [MGTest] M
GROUP BY M.Stylenumber, M.Date) MStock ON MDate.Stylenumber = MStock.Stylenumber AND MDate.MostRecentDate = MStock.Date
答案 2 :(得分:0)
您可以这样做
SELECT B.Stylenumber,SUM(B.Sold),SUM(B.Stock) FROM
(SELECT Stylenumber AS 'Stylenumber',SUM(Sold) AS 'Sold',MAX(Stock) AS 'Stock'
FROM MGTest A
GROUP BY RetailerId,Stylenumber) B
GROUP BY B.Stylenumber
如果您不想使用联接
答案 3 :(得分:0)
我的解决方案,例如Gordon Linoff的解决方案,将使用窗口函数。但就我而言,一切都会绕过RANK窗口功能。
SELECT stylenumber, sold, SUM(stock) totalstock
FROM (
SELECT
stylenumber,
SUM(sold) OVER(PARTITION BY stylenumber) sold,
RANK() OVER(PARTITION BY stylenumber ORDER BY [Date] DESC) r,
stock
FROM MGTest
) T
WHERE r = 1
GROUP BY stylenumber, sold