如何在SQL中从表中添加唯一值

时间:2019-05-28 05:28:55

标签: mysql

我在SQL中有一个看起来像这样的表

Person  brand   brand_spend category    category_spend
0   p1  b1       20           c1           100
1   p1  b2       50           c1           100
2   p2  b1       25           c2           40
3   p1  b3       30           c1           100
4   p1  b2       15           c2           70

我需要根据每个客户在该品牌上所花费的百分比(基于该品牌所在的类别总支出)来标记每个客户。 因此,基本上我想将人p1标记为品牌b1' as percentage spend at 'b1,该品牌应计算为45/140

这是如何实现的。如果我在品牌级别上汇总以查找总类别支出,那么我认为重复行会加起来。

我只想根据存在该品牌的所有类别的品牌总支出来找到该品牌的客户支出。

2 个答案:

答案 0 :(得分:0)

您需要分为两个级别,如下所示:

select person, brand, sum(brand_spend) personspend, spendbrandallcats, 
       round(sum(brand_spend)/spendbrandallcats,3) pbratio from tbl t 
inner join (  -- brand statistics: sum of all spends per brand in all categories
 select brand br, sum(casp) spendbrandallcats from tbl 
 inner join ( -- category statistics: total category sums
   select category ca, sum(brand_spend) casp from tbl group by category
 ) catspend ON ca=category
 group by brand
) brandstats on br=brand
group by person,brand

这些是结果:

person brand personspend spendbrandallcats pbratio
p1     b1    20          140               0.143
p1     b2    65          140               0.464
p1     b3    30          100               0.3
p2     b1    25          140               0.179

在此处查看小演示:https://rextester.com/SVNH27609

答案 1 :(得分:0)

有时候事情并不像看起来那样复杂,简单的查询就可以解决问题。

select person , brand , sum(prsn_brand_spend) ,
sum(category_spend)  , (sum(prsn_brand_spend)/sum(category_spend)) as perc_spend
from tbl group by person , brand 

结果是

person  brand   brand_spend category_spend  perc
    p1  b1       20            100           0.200000
    p1  b2       65            170          0.382353
    p1  b3       30            100          0.300000
    p2  b1       25            40          0.625000