0
WITH A AS (
SELECT SYSDATE date_1,'1' data_1 ,1 item FROM DUAL
UNION
SELECT add_months(SYSDATE,7) date_1,'8'data, '1' item_ FROM DUAL
UNION
SELECT add_months(SYSDATE,6)+ 10, '4' data, '1' item FROM dual
UNION
SELECT add_months(SYSDATE,6) date_1,'3' data, '2' item FROM DUAL
)
SELECT min(date_1), data,item
FROM a 
WHERE date_1 BETWEEN add_months(SYSDATE,6) AND last_day(add_months(SYSDATE,7))
GROUP BY item,data

结果显示项目 1 有两行,但我只想要最小日期一,如何更改代码以在最小(日期)显示一项数据。*我需要日期匹配正确的数据和项目 *。感谢您阅读并期待正确的答案。

我找到了一种不好的方法来调用我的意思:按项目分组并在范围内选择最小 date_1

WITH A AS (
      SELECT SYSDATE date_1,               '1' data, '1' item FROM DUAL
UNION SELECT add_months(SYSDATE,7) date_1, '8' data, '1' item FROM DUAL
UNION SELECT add_months(SYSDATE,6)+ 10,    '4' data, '1' item FROM dual
UNION SELECT add_months(SYSDATE,6) date_1, '3' data, '2' item FROM DUAL
)   
select a.* from A a,(select min(date_1) date_1,item  from A
where 
date_1 BETWEEN add_months(SYSDATE, 6) 
                 AND last_day(add_months(SYSDATE, 7))
                 group by item) b where a.date_1 = b.date_1 and a.item= b.item
4

1 回答 1

3

使用KEEP ... FIRST

SQL> WITH A AS (
  2        SELECT SYSDATE date_1,               '1' data, '1' item FROM DUAL
  3  UNION SELECT add_months(SYSDATE,7) date_1, '8' data, '1' item FROM DUAL
  4  UNION SELECT add_months(SYSDATE,6)+ 10,    '4' data, '1' item FROM dual
  5  UNION SELECT add_months(SYSDATE,6) date_1, '3' data, '2' item FROM DUAL
  6  )
  7  SELECT MIN(date_1), item,
  8         MAX(data) KEEP (DENSE_RANK FIRST ORDER BY date_1) DATA
  9    FROM a
 10   WHERE date_1 BETWEEN add_months(SYSDATE, 6)
 11                    AND last_day(add_months(SYSDATE, 7))
 12   GROUP BY item;

MIN(DATE_1) ITEM DATA
----------- ---- ----
01/06/2013  1    4
22/05/2013  2    3

这将选择日期最短的行子集上的 (MAX) 数据(这里只有一行)。

于 2012-11-22T10:34:30.627 回答