Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在SQL中从表中添加唯一值_Mysql - Fatal编程技术网

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

Mysql 如何在SQL中从表中添加唯一值,mysql,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

我在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
我需要根据每个客户在某个品牌上的支出百分比,根据该品牌所在的总类别支出,对每个客户进行标记。 因此,本质上我想将品牌
b1的个人
p1
标记为“b1
的支出百分比,应计算为45/140”

如何做到这一点。如果我在品牌层面上进行汇总,找出类别支出总额,那么我认为重复的行将累加起来


我只想根据该品牌存在的所有类别的品牌总花费来查找客户在该品牌的花费。

您需要在两个级别上进行分组,如下所示:

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

请看这里的小演示:

有时候事情并不像看上去那么复杂,简单的查询就可以解决问题

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

然后,
b3
上的
p1
的结果应该是
30/100
?@cars10m是的,这是正确的,但是,等等:
p1
在品牌
b1
上总共花费了
20
。其他支出金额(
25
)由
p2
支出。因此,b1上的
p1的正确结果不应该是
20/140
?@Andreas我已经尝试过了。你可以在我补充的答案中找到