【问题标题】:Error for the query statement with CASE and Count带有 CASE 和 Count 的查询语句出错
【发布时间】:2019-12-18 04:49:44
【问题描述】:

这是我原来的查询语句....

 SELECT airline company, country, count(country) "The no.of times the airline visits the country"
 FROM [table]
 GROUP BY airline company, country

我认为这很好用……直到我想在有错误的地方添加一个 case 语句……

修改后,

 Airline Company      : country  : No.Of times
   Singapore Airline  : SG       :   5
   Singapore Airline  : MAL      :   7
   Japan Airline      : SG       :   3
   Japan Airline      : MAL      :   2

在第一个查询语句之后,结果如上所示。无论国家“MAL”的航空公司如何,我都想将 No.of times 列的值更改为 0。所以我尝试将 case 语句添加到 select 中,但它给了我类似 group function is not allowed

 SELECT airline company, country, CASE WHEN country = 'MAL' THEN 0 
                                       ELSE count(country) "The no.of times the airline visits the country" END
 FROM [table]
 GROUP BY airline company, country, CASE WHEN country = 'MAL' THEN 0 
                                       ELSE count(country) "The no.of times the airline visits the country" END

我该如何解决?

【问题讨论】:

  • 您当前的查询应该已经生成了您想要的输出。它有什么问题?

标签: sql oracle case


【解决方案1】:

我会做Conditional Aggregation:

SELECT airline_company, country, 
       COUNT ( CASE WHEN country = 'MAL' THEN NULL 
                    ELSE country 
                    END ) as "# of times the airline visits"
  FROM [table]
 GROUP BY airline_company, country

【讨论】:

  • 它像魔术一样工作......但我想知道为什么我的上面不起作用......
【解决方案2】:

我认为您不需要“group by”中的“CASE”条件来实现您想要的,只需将其保留在select stmt中即可。

我希望这会有所帮助。

【讨论】:

    【解决方案3】:

    我认为您的查询存在多个问题:

    • 如果airline company 是列名,那么它必须以区分大小写的方式用双引号括起来:"airline company" 或"AIRLINE COMPANY"。因为 oracle 不允许直接使用包含空格的列
    • 您试图在 case 表达式结束之前提供别名 "The no.of times the airline visits the country"。您必须在 END 之后为 case 表达式提供别名
    • GROUP BY 子句中不需要 CASE 表达式,因为 case 表达式仅直接使用 GROUP BY 子句中已存在的一列 (COUNTRY)。

    所以您的查询必须如下所示:

    SELECT
        "AIRLINE COMPANY", -- added double quotes
        COUNTRY,
        CASE
            WHEN COUNTRY = 'MAL' THEN 0
            ELSE COUNT(COUNTRY)
        END AS "The no.of times the airline visits the country" 
        -- alias is given after END keyword
    FROM
        YOUR_TABLE
    GROUP BY
        "AIRLINE COMPANY",
        COUNTRY
        -- ,CASE -- commented this
        --    WHEN COUNTRY = 'MAL' THEN 0
        --    ELSE COUNT(COUNTRY)
        -- END AS "The no.of times the airline visits the country"
    

    干杯!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2020-03-28
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多