【问题标题】:How to use case statement in Mode SQL with an Integer column and assign string value如何在 Mode SQL 中使用带有整数列的 case 语句并分配字符串值
【发布时间】:2021-07-26 04:28:20
【问题描述】:
    with user_industries as (
  SELECT DISTINCT company_id, industry, active_seats, revenue, seat_group, received_at FROM (
    SELECT
      nvl(u.clearbit_company_category_industry, u.company_industry) industry,
      u.received_at,
      u.company_id, 
      u.active_seats,
      CASE 
        WHEN u.active_seats >= 1 AND u.active_seats <= 2 THEN 'group_1'
        WHEN u.active_seats >= 3 AND u.active_seats <= 5 THEN 'group_2'
        WHEN u.active_seats >= 6 AND u.active_seats <= 8 THEN 'group_3'
        WHEN u.active_seats >= 9 THEN 'group_4'
      ELSE u.active_seats 
      END seat_group,
      u.revenue,
      row_number() OVER (PARTITION BY u.company_id ORDER BY u.received_at DESC) rownum
    FROM web_application_production_php.users u
  ) where rownum = 1 and received_at >= '2019-07-01'

在运行 Case 语句时,我想分配一个字符串值以在我的报告中使用,我该怎么做?

【问题讨论】:

  • Edit问题并提供minimal reproducible example,即涉及的表或其他对象的CREATE语句(粘贴文本,不要使用图像,不要链接到外部站点),INSERT 用于示例数据 (dito) 的语句以及带有表格文本格式的示例数据的所需结果。并标记您使用的 DBMS。
  • SQL 中没有 CASE 语句 这样的东西。你的意思可能是CASE 表达式
  • 在您的 CASE 中,您似乎已经在使用字符串 'group_1'、'group_2' 等。在 ELSE 部分,您可以 CAST(u.active_seats AS VARCHAR(32))跨度>

标签: sql mode


【解决方案1】:

来自我的同事:嗯,您将 seat_group 分配给一个字符串,除非它不属于某个组,然后您将它分配给一个整数。 SQL 不喜欢这样。 我建议给默认情况一个像'group_0'这样的值,而不是像现在这样的u.active_seats。

    SELECT DISTINCT company_id, industry, active_seats, revenue, seat_group, received_at FROM (
  SELECT
   nvl(u.clearbit_company_category_industry, u.company_industry) industry,
   u.received_at,
   u.company_id, 
   u.active_seats,
   CASE 
    WHEN u.active_seats >= 1 AND u.active_seats <= 2 THEN 'group_1'
    WHEN u.active_seats >= 3 AND u.active_seats <= 5 THEN 'group_2'
    WHEN u.active_seats >= 6 AND u.active_seats <= 8 THEN 'group_3'
    WHEN u.active_seats >= 9 THEN 'group_4'
   ELSE 'group_0'
   END seat_group,
   u.revenue,
   row_number() OVER (PARTITION BY u.company_id ORDER BY u.received_at DESC) rownum
  FROM web_application_production_php.users u
 ) where rownum = 1 and received_at >= '2019-07-01'

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多