oracle - case语句和group by

时间:2016-04-18 23:27:57

标签: sql oracle

嗨 - 我需要您的帮助以下查询。我正在尝试运行下面的查询分组,但我收到以下错误:

  

ORA-00904:“SALES_ID_CO”:标识符无效

你能帮忙吗?非常感谢。

require 'net/http/persistent'

2 个答案:

答案 0 :(得分:2)

SELECT SALES_ID_CO,
       SALES_BRANCH,
       SALES_DATE,
       count(1)
FROM   (
  SELECT sales_date,
         CASE
         WHEN sales_id  LIKE '70%'
         OR   sales_id  LIKE '90%'
         OR   sales_id  LIKE '31%'
         OR   SUBSTR( sales_id, 1, 1 ) IN ( '1', '3', '4', '5' )
           THEN substr(sales_id,2,6)
         WHEN sales_id  LIKE '9%'
           THEN substr(sales_id ,1,6)
         END AS SALES_ID_CO,
         CASE
         WHEN sales_code<> '678 '
         AND  (
              sales_branch LIKE '10%'
           OR sales_branch LIKE '200%'
           OR sales_branch LIKE '300%'
           OR sales_branch LIKE '456%'
         )
           THEN substr(sales_branch,2,6)
         END AS SALES_BRANCH
  from   tbl_sales_cde
  where  sales_country IN ('USA','ASIA','EU')
)
group by SALES_ID_CO, SALES_BRANCH,SALES_DATE

答案 1 :(得分:1)

Oracle不支持group by子句中的列别名。使用子查询:

SELECT SALES_ID_CO, SALES_BRANCH,SALES_DATE, COUNT(*)
FROM (Select sales_date,
             (CASE  WHEN sales_id like '1%'
                    THEN substr(sales_id,2,6)
                    WHEN sales_id  like '3%'
                    THEN substr(sales_id ,2,6)
                    WHEN sales_id  like '4%'
                    THEN substr(sales_id ,2,6)
                    WHEN sales_id  like '5%'
                    THEN substr(sales_id ,2,6)
                    WHEN sales_id  like '9%'
                    THEN substr(sales_id ,1,6)
                    WHEN sales_id  like '70%' OR sales_id  like '90%' OR sales_id  like '31%'
               END) AS SALES_ID_CO,
              (case WHEN sales_branchlike '10%' AND sales_code<> '678 '
                    THEN substr(sales_branch,2,6)
                    WHEN sales_branchlike '200%' AND sales_code<> '678 '
                    THEN substr(sales_branch,2,6)
                    WHEN sales_branchlike '300%' AND sales_code<> '678 '
                    THEN substr(sales_branch,2,6)
                    WHEN sales_branchlike '456%' AND sales_code<> '678 '
                    THEN substr(sales_branch,2,6)
                END) AS SALES_BRANCH
       from tbl_sales_cde
       where sales_country IN ('USA', 'ASIA', 'EU') 
      ) s
group by SALES_ID_CO, SALES_BRANCH,SALES_DATE;

注意:where子句中也有单引号,但这可能是复制问题。