SQL query , How to select a generated field in GROUP BY

无人久伴 提交于 2019-12-25 01:09:39

问题


I am trying to select two things customer_id and segment(based on some logic) which require both of them to be in GROUP BY

I tried using without alias(like giving CASE...END) but it failed as there is MAX in a a GROUP BY fieldname . If I chop off MAX then also it fails to compile .

What should I do to take care off this ?


回答1:


I am not sure why you need "Group by" clause when you are already applying distinct. I strongly believe removing "Group by" clause from your query will give you the result you expect.




回答2:


I believe this was working for me in an SQL Fiddle:

alter session enable parallel query;

SELECT
  t1.CUSTOMER_ID AS CUSTOMER_ID,
  MAX(CASE WHEN t2.event_date=t1.event_date  -- MAX is moved all the way outside
           THEN 'SweepAcquired' 
           ELSE 'NonSweepAcquired'
           END) AS SEGMENT
FROM dsi t1, transaction t2
WHERE t1.CUSTOMER_ID=t2.CUSTOMER_ID(+)
AND t1.MARKETPLACE_ID = '1'
AND lower(t2.event_type(+))='like'
AND lower(t2.SOURCE_TYPE(+))='sweepstakes'
AND t2.SOURCE_ID(+) IS NOT NULL
AND lower(t2.SOURCE_ID(+)) <> 'unknown'
AND t2.ENTITY_ID(+)='1'
GROUP BY t1.CUSTOMER_ID, 
         CASE WHEN t2.event_date = t1.event_date
              THEN 1 
              ELSE 0 
              END
ORDER BY t1.CUSTOMER_ID, SEGMENT
;

For some reason, CASE WHEN MAX() CASE WHEN wasn't working for me. I also simplified a couple things based on duplication in the WHERE clause.

Working fiddle here http://sqlfiddle.com/#!4/630d7/46



来源:https://stackoverflow.com/questions/23490091/sql-query-how-to-select-a-generated-field-in-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!