2

以下に示すようなテーブル構造があります

Temp
 Customer_id | sum

ここで、追加の列 customer_type を含むビューを作成し、顧客が上位 10% の顧客 (合計の降順で、顧客の総数も異なる場合があります) にある場合は値 1 を割り当て、顧客が 10% から 20% の間にある場合は 2、3 を割り当てる必要があります。顧客が 20% から 60% の間にある場合は 4、顧客が 60% から 100% の間にある場合は 4。これどうやってするの?

上位 10% と 10% から 20% の間のデータを抽出できましたが、値を ( source )として割り当てることができませんでした

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

私はこれをこのように解決していました。これまで私を導く彼の答えに対して@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 に答える