I have the following table:
Day | Category | Count |
---|---|---|
D1 | A | 10 |
D1 | B | 20 |
D2 | A | 8 |
D2 | B | 10 |
D3 | A | 6 |
D3 | B | 5 |
I’m trying to create a percentage column by dividing the values in the third column (Count) by the value for D1 across all categories in the second column (Category; in this case 10 and 20 for A and B respectively). This should output something like:
Day | Category | Count | Pct |
---|---|---|---|
D1 | A | 10 | 100% |
D1 | B | 20 | 100% |
D2 | A | 8 | 80% |
D2 | B | 10 | 50% |
D3 | A | 6 | 60% |
D3 | B | 5 | 25% |
The furthest I got is the code below, but I can’t figure out how to do the division by category.
SELECT
day,
category,
count,
count/(SELECT count FROM table WHERE day = 'D1')*100 AS pct
FROM
table
ORDER BY 1
)
3
Answers
this should do what you ask:
I assumed that the denominator will always just be based on "D1", and that combinations of day-category will always be unique.
This should word accurately for you:
This is the same as Asgar’s query but with the unnecessary table derivation removed –