如何使用SQL将权重分配给不同的列?

问题描述 投票:0回答:1

我有一个带有以下标题的数据集:product, sales, material_1, material_2, material_3, style_1, style_2, style_3

基于此数据集,我需要根据销售情况找到最成功的材料和样式。 material_1列应加权为* 3,material_2列应加权为* 2,而material_3列应加权为* 1。样式列也是如此。

因此,基本上,我需要以某种方式对每列进行加权,然后将其乘以该产品的销售额,但是我在弄清楚如何做到这一点上遇到了麻烦。根据我如何看待数据,棉质材料和现代风格应该是最成功的结果。

Product Sales   material_1  material_2  material_3  style_1     style_2 style_3
A   2629715     Cotton      Synthetic   Silk        modern      vintage 
B   2527075     Cotton      leather     Synthetic   modern      Young   
C   678434      Cotton      Synthetic   Silk        modern      Punk    
D   735281      Cotton      leather     Wool        modern      vintage 
E   439256      Cotton      Silk        Denim       young       
F   353630      Silk        Denim       Cotton      Punk        
G   579318      Wool        leather     Cotton      vintage     Young   Chic
H   505876      Cotton      leather     Wool        modern      young   
I   325997      Cotton      Silk                    contemporary        modern  
J   274980      Cotton      Silk                    young       
K   280422      Denim                               young       Punk    Punk
L   293283      Synthetic   Cotton      modern      
M   217215      Cotton      Silk        young       modern  
N   306687      Synthetic   Wool        Cotton      modern      vintage 
O   232490      Cotton      Silk        modern      young   
P   216559      Synthetic   Cotton      modern      
Q   219996      Denim       Cotton      young
sql weighted weighted-average
1个回答
0
投票

一些“预期的输出”会有所帮助,但没有这个,这是一种思考的方式:

WITH materials(weight, material) AS (
  SELECT 3 AS weight, material_1 AS material from mytable 
  UNION ALL
  SELECT 2, material_2 from mytable 
  UNION ALL
  SELECT 1, material_3 from mytable
) 

SELECT material, SUM(weight) AS Weighted_Value
FROM materials
GROUP BY material

这是它的作用:

  1. 将所有material列移动到一个列中,这样您可以更轻松地处理它们

  2. 将您指定的权重分配给每一列

  3. 将每笔销售中与每种物料相关的权重相加,按物料分组在一起

您可以对style字段使用类似的逻辑。试试看,让我知道它是否适合您。

© www.soinside.com 2019 - 2024. All rights reserved.