"按案例排序......"导致ORDER BY子句中的表达式无效

时间:2016-12-29 18:59:44

标签: sql sql-order-by firebird firebird2.5

任何人都可以指出导致我获得

的原因
  

ORDER BY子句中的表达式无效(未包含在聚合函数或GROUP BY子句中)

以下查询出错?这是在Firebird 2.5中。

SELECT  COUNT(*) AS total,
        CASE WHEN YR BETWEEN 1990 AND 1995 THEN '1990-1995' 
             WHEN YR BETWEEN 1996 AND 2000 THEN '1996-2000'
             WHEN YR BETWEEN 2001 AND 2005 THEN '2001-2005'
             ELSE '2005-2017' END AS vehicle_year
FROM bb_history
GROUP BY 2
ORDER BY CASE WHEN YR BETWEEN 1990 AND 1995 THEN 1
              WHEN YR BETWEEN 1996 AND 2000 THEN 2
              WHEN YR BETWEEN 2001 AND 2005 THEN 3
              ELSE 4 END

2 个答案:

答案 0 :(得分:2)

您无法在YR中使用order by列,因为它不是分组结果的一部分。您似乎只想按生成的vehicle_year列进行排序,因此您可以按顺序(或按2)排序:

SELECT  COUNT(*) AS total,
        CASE WHEN YR BETWEEN 1990 AND 1995 THEN '1990-1995' 
             WHEN YR BETWEEN 1996 AND 2000 THEN '1996-2000'
             WHEN YR BETWEEN 2001 AND 2005 THEN '2001-2005'
             ELSE '2005-2017' END AS vehicle_year
FROM bb_history
GROUP BY 2
ORDER BY vehicle_year;

答案 1 :(得分:-2)

您只有两个选定的列,为什么您添加了' 3'和' 4',但这里是查询:

SELECT  COUNT(*) AS total,
        CASE WHEN YR BETWEEN 1990 AND 1995 THEN '1990-1995' 
             WHEN YR BETWEEN 1996 AND 2000 THEN '1996-2000'
             WHEN YR BETWEEN 2001 AND 2005 THEN '2001-2005'
             ELSE '2005-2017' END AS vehicle_year
FROM bb_history
GROUP BY 2
ORDER BY CASE WHEN vehicle_year BETWEEN 1990 AND 1995 THEN 1
              WHEN vehicle_year BETWEEN 1996 AND 2000 THEN 2
              WHEN vehicle_year BETWEEN 2001 AND 2005 THEN 3
              ELSE 4 END