查找销售百分比和回报百分比

时间:2019-08-25 12:12:31

标签: sql sql-server

我在MS SQL DB中有一个表,其中包含任何公司的交易,有两列

  1. sub_cat_code
  2. total_amount

total_amount有时包含正值,有时包含负值。正值表示销售,负值表示退货

现在,我需要使用以下查询找到销售百分比和回报百分比,在返回百分比列中,每个值都相同。任何帮助将是可观的。

Select prod_subcat_code , 
(sum(total_amt)*100 /(select sum(total_amt) from transection)) as 
Sale_pers,
((select sum(total_amt) from transection where total_amt<0)*100/(select 
 sum(total_amt) from transection)) as return_sale
 from transection
 group by prod_subcat_code
 order by Sale_pers desc

4 个答案:

答案 0 :(得分:1)

使用CTE返回表的总销售额和总回报:

with cte as (
  select 
    sum(case when total_amount > 0 then total_amount else 0 end) total_sales,
    sum(case when total_amount < 0 then total_amount else 0 end) total_returns
  from transection
)
select prod_subcat_code , 
  100.0 * sum(case when total_amount > 0 then total_amount else 0 end) / (select total_sales from cte) as sale_perc,
  100.0 * sum(case when total_amount < 0 then total_amount else 0 end) / (select total_returns from cte) as return_perc
from transection
group by prod_subcat_code

请参见demo

答案 1 :(得分:0)

如果我理解正确,您只想划分两个聚合值:

Select prod_subcat_code,
       sum(total_amt) as net_sales,
       sum(case when total_amt > 0 then total_amt else 0 end) as sales,
       sum(case when total_amt < 0 then total_amt else 0 end) as returns,
       (sum(case when total_amt > 0 then total_amt else 0 end) /
        nullif(sum(total_amt), 0)
       ) as sales_ratio,
       (sum(case when total_amt < 0 then total_amt else 0 end) /
        nullif(sum(total_amt), 0)
       ) as return_ratio
from transection
group by prod_subcat_code;

答案 2 :(得分:0)

您可能希望将查询更改为此,以获得所需结果:

Select  prod_subcat_code, 
        sum(case when total_amt > 0 then total_amt else 0 end) as sales,

        (sum(case when total_amt > 0 then total_amt else 0 end) /
        (sum(total_amt)) ) * 100 as sales_Percent,

        sum(case when total_amt < 0 then total_amt else 0 end) as [returns],

        (sum(case when total_amt < 0 then total_amt else 0 end) /
        (sum(total_amt)) ) * 100 as Return_Percent
 from transection
 group by prod_subcat_code
 order by sales_Percent desc

答案 3 :(得分:0)

希望它会对您有所帮助,

browser = webdriver.Chrome()
browser.get("http:/link") 
frame_id = 'frame'
wait = WebDriverWait(browser, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, frame_id)))