'SQL Querying of Data by grouping with only one main variable(Store) and finding the percentage of customers in other variable
Tables - Store
| Stores | Date | Customer_ID |
|---|---|---|
| A | 01/01/2020 | 1111 |
| C | 01/01/2020 | 1111 |
| F | 02/01/2020 | 1234 |
| A | 02/01/2020 | 1111 |
| A | 02/01/2020 | 2222 |
Tables - Customer
| Customer_ID | Age_Group | Income_Level |
|---|---|---|
| 1111 | 26-30 | Low |
| 1234 | 25 and below | Mid |
| 2222 | 31-60 | High |
I want to know how I can get this output.
| Stores | Age_Group | Percentage_by_Age | Income_Level | Percentage_By_Income |
|---|---|---|---|---|
| A | 25 and below | 10 | Low | 80 |
| A | 25 and below | 10 | Mid | 10 |
| A | 25 and below | 10 | High | 10 |
| A | 26 - 30 | 42 | Low | 15 |
| A | 26 - 30 | 42 | Mid | 65 |
| A | 26 - 30 | 42 | High | 20 |
| A | 31 - 60 | 48 | Low | 30 |
| A | 31 - 60 | 48 | Mid | 50 |
| A | 31 - 60 | 48 | High | 20 |
I am using SQL to query from different tables. First I need to aggregate the number of customers by stores, then in each store, I want to find out how many customers visited Store A in a particular age group(25 and below), and how many of them are in which income level.
May I know how I can go about solving this query?
Thanks.
My current solution/thought process
SELECT
stores AS Stores,
Age_Group AS Age,
Income_Level AS Income
COUNT(DISTINCT(Customer_ID)) AS Number_of_Customers
FROM tables JOIN tables....
GROUP BY Stores, Ages, Income;
And then manually calculating the percentages. But it doesn't seem right. Is there a way to produce an example output table using just SQL?
Solution 1:[1]
SELECT
s.Stores AS Stores,
c.age_group AS Age,
a.income_level AS Affluence,
CAST(COUNT(DISTINCT c.Customer_ID) AS numeric)*100/SUM(CAST(COUNT(DISTINCT c.Customer_ID) AS numeric)) OVER(PARTITION BY s.Stores ) AS Perc_of_Members
This is what I did in the end.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lemon |
