Here's an obfuscated version of something I've been trying to do at work. Say I have been given this month's data for customers in my shop - how much they've spent split by the food type:
CUSTOMER FOOD_TYPE FOOD_TYPE_VALUE
1 SWEET 52.6
1 SAVOURY 31.0
1 DAIRY 45.8
1 DRINKS 12.1
2 SWEET 15.1
2 SAVOURY 44.1
2 DRINKS 23.4
3 SWEET 95.7
3 SAVOURY 20.0
3 DAIRY 10.8
3 DRINKS 57.1
It has been decided that Customer 3 is our ideal customer as he fits the demographic profile, and we want to track month by month, how everybody's distribution of shopping preferences differs from his.
I can get the percentage allocation for each food type for each customer with:
SELECT
c1.customer,
c1.food_type,
100 * c1.food_type_value / sum(c2.food_type_value)
FROM
mytable c1 INNER JOIN mytable c2
ON c1.customer = c2.customer
group by c1.customer, c1.food_type, c1.food_type_value
But I am having trouble constructing a query that will give me a further column with the matching percentage values for my ideal customer. ie:
CUSTOMER FOOD_TYPE FOOD_TYPE_PERC IDEAL_PERC
1 SWEET 37 52
1 SAVOURY 22 11
1 DAIRY 32 6
1 DRINKS 9 31
Any tips on how I can achieve this without too much mess?