问题
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