문제

Thanks in advance for taking a look at my issue. What I am trying to to is take a users transaction history and sum the revenue from all of their total orders, then group these total orders into segments, and count how many users are in each segment.

I am basically using a single table to aggregate revenue data. The REVENUE table for all intents and purposes is structured like this.

Columns | Sample Data
ID|123
ORDER_NUMBER|123ABC
REVENUE|10

Each record is structure like this and there is a single record for each purchase. I use the following SQL to aggregate REVENUE by ID

SELECT ID, SUM(ROUND(REVENUE)) as Total_Rev
FROM REVENUE
GROUP BY ID
ORDER BY ID

I get and output like this
ID | Total_Rev
1002436 | 11
1002437 | 12
1002438 | 5
10024399 | 2
100244 | 4
10024544 | 21
10024584 | 16
10024624 | 4
1002478 | 8
10024789 | 12
10024843 | 4
10024944 | 9

So what I am trying to do is group ID's by Total_rev into 3 predefined segments then I want to count the user ID's in each segment.

My segments are defined by Total_Rev like this:
Low: 1-5
Med: 6-20
High: 21+

I am just not sure how to create the proper SQL to do this segmentation exercise. Again thanks for taking a look and I will be happy to provide more detail or respond to any feedback on this issue.

Thanks, -Chris

도움이 되었습니까?

해결책

Try it like this:

SELECT ID, LMH FROM (
    SELECT ID, SUM(ROUND(REVENUE)) as Total_Rev, 'LOW' as LMH
       FROM REVENUE
       GROUP BY ID
       HAVING Total_Rev > 0 AND Total_Rev <= 5
    UNION ALL
    SELECT ID, SUM(ROUND(REVENUE)) as Total_Rev, 'Med' as LMH
       FROM REVENUE
       GROUP BY ID
       HAVING Total_Rev > 5 AND Total_Rev <= 20
    UNION ALL
    SELECT ID, SUM(ROUND(REVENUE)) as Total_Rev, 'High' as LMH
       FROM REVENUE
       GROUP BY ID
       HAVING Total_Rev > 20) as subquery
    ORDER BY ID

I think there could be more elegant ways to do the same, but my statement should work too =)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top