如何仅获取Min数据的值

时间:2016-11-03 02:46:00

标签: sql sql-server sql-server-2008 sql-server-2005

我的查询如下图所示将得到结果

SELECT Dept,
       Item,       
       Month,
       OpenQty,
       OpenVal
FROM   StockTransaction
WHERE  year = 2016 and
       month between 1 and 10

This is the result from my query above

实际上我想要的结果是只有每个部门的最小月份,项目将包含 openqty openval 值。除此之外,它将保持零值。

enter image description here

如何编写查询以获得如上图所示的结果?

1 个答案:

答案 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;