Oracle分組查詢
摘要:
分組查詢,且只取每一組內的一條最新的記錄
需求:查詢 code 為a,b,c且在有效時間段內的每個code最新的一條記錄(code不是主鍵)
select * from (select code
col1,
col2,
row_number() over (pa...
分組查詢,且只取每一組內的一條最新的記錄
需求:查詢 code 為a,b,c且在有效時間段內的每個code最新的一條記錄(code不是主鍵)
select * from (select code col1, col2, row_number() over (partition by code order by time desc) rank from t_order where type= '107' and to_char(sysdate, 'yyyymmdd-hh24:mi:ss') <= validuntilTime and code in ('a','b','c') ) where rank = 1
<!-- more -->
-
其中下面程式碼含義是將時間在有效時間段內(
to_char(sysdate, 'yyyymmdd-hh24:mi:ss') <= validuntilTime
)且code為a,或b,或c(code in('a','b','c')
)的所有記錄根據code分組(partition by code
),且組內的順序是根據時間的逆序排列(order by time desc
)
(select code col1, col2, row_number() over (partition by code order by time desc) rank from t_order where type= '107' and to_char(sysdate, 'yyyymmdd-hh24:mi:ss') <= validuntilTime and code in ('a','b','c') )
- 上面執行結果是類似下面表格效果
CODE | COL1 | COL2 | RANK |
---|---|---|---|
a | xxx | xxx | 1 |
a | xxx | xxx | 2 |
a | xxx | xxx | 3 |
b | xxx | xxx | 1 |
b | xxx | xxx | 2 |
c | xxx | xxx | 1 |
c | xxx | xxx | 2 |
c | xxx | xxx | 3 |
c | xxx | xxx | 4 |
-
然後將其作為子查詢,在外層套一個
select * from (上面的程式碼) where rank = 1
就能將每一組內的一條最新的記錄查詢出來了