我需要对查询结果进行排序
我的查询
SQL> SELECT DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY'),
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
group by processed_dt, process_name, process_event_code;
示例
Actual data
---------------------------------------------------------------------
Processed_dt | Process_name | Process_event_code
---------------------------------------------------------------------
10-Jan-2014 |ABC |140
12-Jan-2014 |BCD |240
10-Jan-2014 |BCD |240
15-Feb-2013 |ABC |140
10-Jan-2014 |ABC |140
10-Jan-2014 |BCD |240
....
....
我使用DISTINCT TO_CHAR()
来避免重复
Result
---------------------------------------------------------------------
Processed_dt | Process_name | Process_event_code
---------------------------------------------------------------------
10-Jan-2014 |ABC |140
12-Jan-2014 |BCD |240
10-Jan-2014 |BCD |240
15-Feb-2013 |ABC |140
....
现在我需要按processed_dt
订购。
我试过
SQL> SELECT DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY'),
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
GROUP BY processed_dt, process_name, process_event_code
ORDER BY processed_dt;
SQL> SELECT DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY'),
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
GROUP BY processed_dt, process_name, process_event_code
ORDER BY 1;
SQL> SELECT DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY'),
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
GROUP BY processed_dt, process_name, process_event_code
ORDER BY DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY');
SQL> SELECT DISTINCT TO_CHAR(processed_dt ,'DD/MMM/YYYY') AS abcxyz,
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
GROUP BY processed_dt, process_name, process_event_code
ORDER BY abcxyz;
ORDER BY 1
我不确定这是对还是错。我在谷歌找到了这个。
我在存储过程中使用此查询,需要进行一些计算。
所有查询都无效。我正在使用Oracle DB。
感谢您对此的帮助。
CVSR Sarma
答案 0 :(得分:1)
ORDER BY的行为完全符合预期 - 您按照包含DD/MM/YYYY
格式的日期的字符串进行排序,Oracle很乐意将其排序为
10/02/2014
11/01/2014
15/01/2014
...
要获得正确的行为,您必须按日期排序:
SELECT formatted_date, process_name, process_event_code
FROM (
SELECT DISTINCT
trunc(processed_dt), -- this is our sorting column
TO_CHAR(processed_dt ,'DD/MM/YYYY') as formatted_date,
process_name, process_event_code
FROM process_hist_view
WHERE process_id ='XXX'
ORDER BY trunc(processed_dt)
)
BTW:我删除了GROUP BY,因为GROUP BY与DISTINCT结合使用没有任何意义。