Oracle SQL - 获取有关非唯一数据

时间:2017-09-27 06:15:50

标签: sql oracle

以下是表格中的记录示例 -

ITEM_NAME   STORAGE_CODE   STOCK   DATE
ABC         2233           170     27/09/2017
ABC         2233           270     15/09/2017
DEF         2233           120     23/09/2017
DEF         2233           110     11/09/2017
GHI         2233           50      15/09/2017

预期结果:

ITEM_NAME   STORAGE_CODE   STOCK   DATE
ABC         2233           170     27/09/2017
DEF         2233           120     23/09/2017
GHI         2233           50      15/09/2017

我尝试过使用以下查询:

Select ITEM_NAME, STORAGE_CODE, STOCK, MAX(DATE) 
FROM ITEM_TABLE 
WHERE ITEM_NAME IN ('ABC','DEF','GHI' .........) 
GROUP BY ITEM_NAME, STORAGE_CODE, STOCK

这不起作用,因为股票价值不是唯一的。

请注意:我使用ITEM_NAME IN (),因为我需要某些特定项目的输出。

4 个答案:

答案 0 :(得分:0)

如果您只想获得select top日期,可以在查询中添加order bymax,如下所示:

SELECT TOP 1
       ITEM_NAME,
       STORAGE_CODE,
       STOCK,
       MAX(DATE)
FROM ITEM_TABLE
WHERE ITEM_NAME IN('ABC', 'DEF', 'GHI')
GROUP BY ITEM_NAME,
         STORAGE_CODE,
         STOCK
ORDER BY DATE DESC

编辑:使用row_num

SELECT T.ITEM_NAME,
       T.STORAGE_CODE,
       T.STOCK,
       T.DATE
FROM
(
    SELECT ITEM_NAME,
           STORAGE_CODE,
           STOCK,
           DATE,
           ROW_NUMBER() OVER(PARTITION BY ITEM_NAME,
                                          STORAGE_CODE ORDER BY DATE DESC) AS part
    FROM ITEM_TABLE
    WHERE ITEM_NAME IN('ABC', 'DEF', 'GHI')
) T
WHERE part = 1;

答案 1 :(得分:0)

我认为像这样的查询应该有效:

select 
    *
from (
    select *,
        row_number() over (partition by ITEM_NAME, STORAGE_CODE order by DATE desc) as seq
    from ITEM_TABLE
    where ITEM_NAME in ('ABC','DEF','GHI' .........)
) t
where seq = 1

答案 2 :(得分:0)

您可以像以下

一样使用Oracle row_number() over(partition by)
select ITEM_NAME
     , STORAGE_CODE
     , STOCK
     , DATE
from 
(
    select ITEM_NAME
        , STORAGE_CODE
        , STOCK
        , DATE
        , row_number() over(partition by ITEM_NAME order by DATE desc) as rn
    from ITEM_TABLE
) s
where rn = 1

答案 3 :(得分:0)

一种方法是使用max获取内部查询中DATE1列的stock值和外部查询中的相应join值,如下所示。

SELECT t.*
    ,t1.STOCK
FROM (
    SELECT ITEM_NAME
        ,STORAGE_CODE
        ,MAX(DATE1) AS DATE1
    FROM table1
    GROUP BY ITEM_NAME
        ,STORAGE_CODE
    ORDER BY ITEM_NAME
    ) t
INNER JOIN table1 t1 ON t.ITEM_NAME = t1.ITEM_NAME
    AND t.STORAGE_CODE = t1.STORAGE_CODE
    AND t.DATE1 = t1.DATE1

<强>结果:

ITEM_NAME   STORAGE_CODE         DATE1           STOCK
------------------------------------------------------
ABC            2233       27.09.2017 00:00:00     170
DEF            2233       23.09.2017 00:00:00     120
GHI            2233       15.09.2017 00:00:00     50

<强> DEMO