我遇到了oracle查询的问题。在此查询中,我想显示状态恢复,其中记录采用seq coloumn和extern coloumn的最大值。这是我的疑问:
select x.order_id, z.status_resume,
max(y.seq) as seq2,
max(y.extern_order_status) as extern
from t_order_demand x
JOIN t_order_log y ON x.order_id=y.order_id
JOIN p_catalog_status z ON z.status_code_sc=y.extern_order_status
and x.order_id like '%1256%'
group by x.order_id, z.status_resume;
这就是结果:
订单ID status_resume seq extern
1256进程2 4
1256注册1 2
1256预先注册0 1
我希望结果只是状态恢复基于seq和extern的最大值。我该怎么做?帮帮我..谢谢。
订单id status_resume seq extern
1256 proccess 2 4
答案 0 :(得分:1)
WITH t AS
(SELECT x.order_id
,z.status_resume
,MAX(y.seq) AS seq2
,MAX(y.extern_order_status) AS extern
FROM t_order_demand x
JOIN t_order_log y
ON x.order_id = y.order_id
JOIN p_catalog_status z
ON z.status_code_sc = y.extern_order_status
AND x.order_id LIKE '%1256%'
GROUP BY x.order_id
,z.status_resume)
SELECT *
FROM t
WHERE (t.seq || t.extern) = (SELECT MAX(tt.seq || tt.extern) FROM t tt);
可能会为你工作。
答案 1 :(得分:0)
WITH data AS
(
SELECT x.order_id,
z.status_resume,
Max(y.seq) AS seq2,
Max(y.extern_order_status) AS extern
FROM t_order_demand x
join t_order_log y
ON x.order_id=y.order_id
join p_catalog_status z
ON z.status_code_sc=y.extern_order_status
AND x.order_id LIKE '%1256%'
GROUP BY x.order_id,
z.status_resume )
SELECT *
FROM data
WHERE seq || extern =
(select max(seq || extern)
FROM data)
/
要验证的简单测试用例:
SQL> WITH DATA AS(
2 SELECT 1 col1, 2 col2 FROM dual UNION ALL
3 SELECT 5, 7 FROM dual
4 )
5 SELECT * FROM DATA
6 where col1||col2 = (select max(col1||col2) from data)
7 /
COL1 COL2
---------- ----------
5 7
SQL>
答案 2 :(得分:0)
您可以使用分析函数RANK:
select order_id, status_resume, seq2, extern
from (
select x.order_id, z.status_resume,
max(y.seq) as seq2,
max(y.extern_order_status) as extern,
rank() over(partition by x.order_id, z.status_resume order by max(y.seq) desc, max(y.extern_order_status) desc) rnk
from t_order_demand x
JOIN t_order_log y ON x.order_id=y.order_id
JOIN p_catalog_status z ON z.status_code_sc=y.extern_order_status
and x.order_id like '%1256%'
group by x.order_id, z.status_resume
) where rnk = 1;
但目前尚不清楚最多两个字段是什么意思。总和?上面的查询使用max seq
检索行,如果多行具有相同的seq
,则只检索max extern_order_status
行。