SQL-在MIN(Date)处取对应的值

时间:2018-07-03 13:53:17

标签: sql sql-server

我有一个数据集,其中包含给定日期的给定仓库的仓库位置,日期和库存水平。

如何构造一个SQL查询,最后在每个仓库的最早日期列出不同的位置及其库存水平?我在想类似...

选择Warehouse_id,(inventory_amt,min(date)为TRUE)作为库存

FROM库存表

按Warehouse_id分组

3 个答案:

答案 0 :(得分:1)

我喜欢为此使用row_number()top (1) with ties

SELECT TOP (1) WITH TIES it.*
FROM inventory_table it
ORDER BY ROW_NUMBER() OVER (PARTITION BY warehouse_id ORDER BY date DESC);

您也可以将其表示为:

select it.*
from inventory_table it
where it.date = (select max(it2.date)
                 from inventory_table it2
                 where it2.warehouse_id = it.warehouse_id
                );

答案 1 :(得分:0)

尝试这样的事情

select warehouse_id,....
from  inventory_table t1
inner join (
select warehouse_id, min(date) from  inventory_table group py warehouse_id
) min
on t1.warehouse_id=min.warehouse_id

答案 2 :(得分:0)

这对我有用:

proc sql;
CREATE TABLE inventory_by_warehouse AS
SELECT
    a.warehouse_id
    ,a.inventory_amt
FROM inventory_table as a
WHERE a.date = 
    (SELECT min(date)
    FROM inventory_table
    WHERE warehouse_id = a.warehouse_id);
quit;