递增ORDER BY语句

时间:2015-04-30 20:44:58

标签: mysql sql sql-order-by

我有一个如下所示的查询:

SELECT ElapsedTime, COUNT(SurgeryID) as numberOfOps
FROM Table
WHERE Doctor = 'Dr. ABC'
AND numberOfOps > 5
GROUP BY ElapsedTime
ORDER BY CASE
  WHEN ElapsedTime = 'Preoperative' THEN 1
  WHEN ElapsedTime = '2 Weeks' THEN 2
  WHEN ElapsedTime = '6 Weeks' THEN 3
  WHEN ElapsedTime = '3 Months' THEN 4
  WHEN ElapsedTime = '6 Months' THEN 5
  WHEN ElapsedTime = '1 Year' THEN 6
  WHEN ElapsedTime = '2 Years' THEN 7
  WHEN ElapsedTime = '3 Years' THEN 8
  WHEN ElapsedTime = '4 Years' THEN 9
  WHEN ElapsedTime = '5 Years' THEN 10
  WHEN ElapsedTime = '6 Years' THEN 11
  WHEN ElapsedTime = '7 Years' THEN 12
  WHEN ElapsedTime = '8 Years' THEN 13
  WHEN ElapsedTime = '9 Years' THEN 14
  WHEN ElapsedTime = '10 Years' THEN 15
  ELSE ElapsedTime END ASC

如果ABC博士没有任何结果w /' DaysElapsed' =='术前',ORDER BY的其余部分被忽略 - 如下面的结果:

'5 Years,6 Years,7 Years,8 Years,10 Years,2 Weeks,6 Weeks,3 Months,6 Months,1 Year,2 Years,3 Years,4 Years,Unknown'

如何使这个ORDER BY子句更健壮?

有没有办法在语句中包含递增变量,例如

SELECT ElapsedTime, COUNT(SurgeryID) as numberOfOps
FROM Table
WHERE Doctor = 'Dr. ABC'
GROUP BY Time
var i = 0;
ORDER BY CASE
  WHEN ElapsedTime = 'Preoperative' THEN ++i
  WHEN ElapsedTime = '2 Weeks' THEN ++i
  WHEN ElapsedTime = '6 Weeks' THEN ++i
  WHEN ElapsedTime = '3 Months' THEN ++i
  .          .          .          .
  .          .          .          .
  .          .          .          .
  .          .          .          .   
  WHEN ElapsedTime = '10 Years' THEN ++1
  ELSE ElapsedTime END ASC

我理解SQL并不允许这样的事情,但这就是我所寻求的功能类型。

由于

3 个答案:

答案 0 :(得分:0)

您可能编写一个PLSQL函数将DaysElapsed varchars转换为数字,然后像这样使用它:

SELECT Time
  FROM Table
 WHERE Doctor = 'Dr. ABC'
 GROUP BY Time
 ORDER DaysElapsedToOrderBy(DaysElapsed);

函数本身可能如下所示。 注意这是非常基本的,可能会导致错误 - 仅将其作为进一步改进的示例实现。

CREATE FUNCTION DaysElapsedToOrderBy(psDaysElapsed VARCHAR) RETURN NUMBER IS

    nCount        NUMBER;
    sIntervalType VARCHAR(100);

BEGIN

    -- Split DaysElapsed to number of intervals and intervalType
    nCount := TO_NUMBER(SUBSTR(psDaysElapsed, 1, 1));
    sIntervalType := SUBSTR(psDaysElapsed, 3);

    -- calculate order by value
    CASE sIntervalType

        WHEN 'days'   THEN RETURN nCount
        WHEN 'months' THEN RETURN nCount * 10
        WHEN 'years'  THEN RETURN nCount * 100
        ...

    END

END;

答案 1 :(得分:0)

您可以使用光标(可以获得I ++逻辑)来填充CTE / Temp表/表变量,然后将其加入到表中,并根据查询,您可以按列排序选择。我回到家时回答很长的问题。

答案 2 :(得分:0)

尝试以下查询

SELECT ElapsedTime, SURGERY_COUNT   from (select case ElapsedTime WHEN 'Preoperative' THEN 1 
                        WHEN '2 Weeks'       THEN 2
                        WHEN '2 Years'       THEN 3 
                        WHEN '10 Years' THEN 4
                        ELSE 0 END AS  surgery_order , ElapsedTime, COUNT(SurgeryID) as SURGERY_COUNT from test_table 
where Doctor = 'Dr. ABC' and numberOfOps > 5 GROUP BY surgery_order, ElapsedTime order by surgery_order asc) as DATA_TABLE