2

我的表结构如下所示

Temp
 Customer_id | sum

现在我必须创建带有额外列 customer_type 的视图,如果客户位于前 10% 的客户中,则分配值 1(总和的降序,客户总数可能会有所不同),如果客户位于 10%-20% 之间,则分配值为 2,3如果客户在 20%-60% 之间,如果客户在 60%-100% 之间,则为 4。我怎样才能做到这一点?

我只能提取前 10% 和 10% - 20% 之间的数据,但无法将值分配为(来源

SELECT * FROM temp WHERE sum >= (SELECT sum FROM temp t1 
WHERE(SELECT count(*) FROM temp t2 WHERE t2.sum >= t1.sum) <= 
(SELECT 0.1 * count(*) FROM temp));

和(不是有效的只是增强上面的代码)

select * from temp t1 
where (select count(*) from temp t2 where t2.sum>=t2.sum)
>= (select 0.1 * count(*) from temp) and (select count(*) from temp t2 where t2.sum>=t1.sum)
<= (select 0.2 * count(*) from temp);

示例数据可在sqlfiddle.com上获得

4

2 回答 2

2

这应该可以帮助你。您需要获取总和和总行数的行号。我相信你可以很容易地弄清楚其余的。

SELECT  
    *,
    @curRow := @curRow + 1 AS row_number,
    (@curRow2 := @curRow2 + 1) / c as pct_row
FROM    
    temp t
    JOIN (SELECT @curRow := 0) r
    JOIN (SELECT @curRow2 := 0) r2
    join (select count(*) c from temp) s
order by 
    sum desc

这是基于这个答案

于 2013-05-25T08:10:10.737 回答
2

我已经像这样解决了这个问题。感谢@twn08的回答,指导我做到了这一点。

select customer_id,sum,case 
when pct_row<=0.10 then 1
when pct_row>0.10 and pct_row<=0.20 then 2
when pct_row>0.20 and pct_row<=0.60 then 3
when pct_row>0.60 then 4
end as customer_label from (
select customer_id,sum,(@curRow := @curRow+1)/c as pct_row
from temp t 
jOIN (SELECT @curRow := 0) r
JOIN (SELECT @curRow2 := 0) r2 
join (select count(*) c from temp) s
order by sum desc) p;

我不知道这是否是有效的方法,但适用于小数据集。

于 2013-05-25T16:48:06.183 回答