代码之家  ›  专栏  ›  技术社区  ›  user3407267

按类分组SQL查询

  •  3
  • user3407267  · 技术社区  · 6 年前

    我有一个表(原因表)和数据(例如):

    request_id          created_time            type             detail
    asdas232          2018-07-29 00:00:01      NO_VALID        No valid offer for id asdas232
    aseeas232         2018-07-29 00:00:02      NO_VALID        Not default offer for id aseeas232
    

    我试图根据细节来计算,比如(上面的):

    invalidOffer = 1
    NoDefaultOffer = 1
    

    我试过:

    SELECT detail, count(*)
    FROM reason_table 
    where "type" like '%NO_VALID%'
    and created_time >=  '2018-07-29 00:00:00'
    and created_time <=  '2018-07-29 00:00:10'
    GROUP BY
        CASE
            WHEN detail LIKE '%invalid%' THEN 'invalidOffer'
            WHEN detail LIKE '%default%' THEN 'NoDefaultOffer'
            ELSE NULL
        END
    

    但是说错话 SQL Error [500310] [42803]: [ Invalid operation: column "detail" must appear in the GROUP BY clause or be used in an aggregate function;

    有什么能帮我找到我做错了什么吗? 我正在使用DBeaver从redshift查询数据

    1 回复  |  直到 6 年前
        1
  •  4
  •   Gordon Linoff    6 年前

    将表达式移到 select :

    SELECT (CASE WHEN detail LIKE '%invalid%' THEN 'invalidOffer'
                 WHEN detail LIKE '%default%' THEN 'NoDefaultOffer'
            END) as detail_group,
            count(*)
    FROM reason_table 
    WHERE "type" like '%NO_VALID%' AND
          created_time >=  '2018-07-29 00:00:00' AND
          created_time <=  '2018-07-29 00:00:10'
    GROUP BY (CASE WHEN detail LIKE '%invalid%' THEN 'invalidOffer'
                   WHEN detail LIKE '%default%' THEN 'NoDefaultOffer'
              END);