占T-SQL总销售额的80%

时间:2018-01-26 07:47:56

标签: sql sql-server

我有这样的数据

Brand Name  Sales Cost  Mkt
Brand1  3312    ABC
Brand2  3490    ABC
Brand3  7794    ABC
Brand4  8325    ABC
Brand5  3915    ABC
Brand6  6494    ABC

预期输出应该是这样的:

Brand Name  Sales Cost  Mkt Percentage
Brand1  3312    ABC 10%
Brand2  3490    ABC 17%
Brand3  7794    ABC 80%
Brand4  8325    ABC 89%
Brand5  3915    ABC 12%
Brand6  6494    ABC 59%

我想找出拥有ABC市场80%销售额的品牌?建议请

2 个答案:

答案 0 :(得分:4)

我想你想要窗口功能。我假设brandX可能会在您的数据中多次出现一个mkt(即使您的示例中没有这样的行)

select brand, 
       mkt,
       sum(sales), 
       sum(cast(sales as float))/sum(cast(sum(sales) as float)) over (partition by mkt) * 100 
from data
group by brand, mkt

dbfiddle demo

如果你想要那些拥有80%以上的人使用子查询和

select *
from
(
    select brand, 
           mkt,
           sum(sales) sumsales, 
           sum(cast(sales as float))/sum(cast(sum(sales) as float)) over (partition by mkt) * 100 percentsales
    from data
    group by brand, mkt
) t
where percentsales > 80

答案 1 :(得分:2)

试试这个:

select * from (
select [Brand Name],
       [Sales],
       [Cost],
       [Sales]/(sum([Sales]) over (partition by (select null))) [Mkt Percentage]
from MY_TABLE
) [a] where [Mkt Percentage] >= 0.8