简体   繁体   中英

Group by like SQL query

I have a table (reason_table) with data (eg) :

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

I am trying to get the count based on detail like(for the above) :

invalidOffer = 1
NoDefaultOffer = 1

I tried :

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

but getting error saying SQL Error [500310] [42803]: [ Invalid operation: column "detail" must appear in the GROUP BY clause or be used in an aggregate function;

Can some help me find what I am doing wrong here ? I am using DBeaver to query data from redshift

Move the expression to the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM