我的查询如下图所示将得到结果
SELECT Dept,
Item,
Month,
OpenQty,
OpenVal
FROM StockTransaction
WHERE year = 2016 and
month between 1 and 10
实际上我想要的结果是只有每个部门的最小月份,项目将包含 openqty 和 openval 值。除此之外,它将保持零值。
如何编写查询以获得如上图所示的结果?
答案 0 :(得分:3)
您可以使用窗口功能:
SELECT Dept, Item, Month,
(CASE WHEN row_number() over (partition by dept, item order by month) = 1
THEN OpenQty ELSE 0
END) as OpenQty,
(CASE WHEN row_number() over (partition by dept, item order by month) = 1
THEN OpenVal ELSE 0
END) as OpenVal
FROM StockTransaction
WHERE year = 2016 and
month between 1 and 10;