Sql按多列排序

时间:2012-12-15 23:09:26

标签: sql oracle sql-order-by

我有以下结果

VendorName | IncidentID | IncidentStatus | IncidentDate
-------------------------------------------------------
XYZ        | 100        |     Open       | 02-JUN-2011    
XYZ        | 101        |     Open       | 03-JUN-2011  
ABC        | 102        |     Open       | 01-JUN-2011  
XYZ        | 103        |     Open       | 01-APR-2011  
ABC        | 105        |     Open       | 05-JUN-2011 

我想订购有最新事件的VendorName。供应商ABC有最新事件因此它应首先针对同一供应商的所有其他事件,然后是下一个供应商,所有事件都按降序排列。期望的结果是这样的 -

VendorName | IncidentID | IncidentStatus | IncidentDate  
-------------------------------------------------------
ABC        | 105        |     Open       | 05-JUN-2011 
ABC        | 102        |     Open       | 01-JUN-2011
XYZ        | 101        |     Open       | 03-JUN-2011 
XYZ        | 100        |     Open       | 02-JUN-2011    
XYZ        | 103        |     Open       | 01-APR-2011  

ORDER BY IncidentDate desc, VendorName未提供所需的输出。有什么帮助吗?

4 个答案:

答案 0 :(得分:26)

使用分析函数:

SELECT *
FROM(
    SELECT 
        VendorName, 
        IncidentID, 
        IncidentStatus, 
        IncidentDate, 
        MAX(IncidentDate) OVER (PARTITION BY VendorName) maxDate
    FROM yourTable
) t
ORDER BY t.maxDate DESC, t.VendorName ASC, t.IncidentDate DESC

参考: http://docs.oracle.com/javadb/10.8.2.2/ref/rrefsqlj13658.html http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions003.htm http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm

答案 1 :(得分:4)

这样做......

ORDER BY MAX(INCIDENTDATE) OVER (PARTITION BY VENDORNAME) DESC, INCIDENTDATE DESC

...但我不确定ORDER BY中是否允许使用分析函数。如果不是,请在子查询中计算并按主查询中的顺序...

select ...
from   (
  select Max(incidentdate) over (partition by vendorname) max_incidentdate_by_vendor,
         ...)
order by max_incidentdate_by_vender desc, incidentdate desc

答案 2 :(得分:0)

如果您正在安装RAC

set linesize 300
column REDOLOG_FILE_NAME format a50
SELECT
    a.INST_ID,
    a.GROUP#,
    a.THREAD#,
    a.SEQUENCE#,
    a.ARCHIVED,
    a.STATUS,
    b.MEMBER    AS REDOLOG_FILE_NAME,
    (a.BYTES/1024/1024/1024) AS SIZE_GB
FROM gv$log a
JOIN gv$logfile b ON a.Group#=b.Group# 
AND a.INST_ID=b.INST_ID 
ORDER BY a.INST_ID ASC, a.GROUP# ASC;

答案 3 :(得分:-2)

if (state.isPrimaryJumping && 
    state.timeUntilCanJump == 0 && 
    state.isStartPrimaryJumping && 
    state.jumpIsLoaded && 
    state.primaryJumpsSinceTouchedGround < moveStats.maxJumps) 
{
  // do awesome jumping stuff
}