sql - 查找销售百分比和退货百分比
问题描述
我在 MS SQL DB 中有一个表,其中包含任何公司的交易,有两列
sub_cat_code
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
解决方案
使用返回表的总销售额和总回报的 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
请参阅演示。
推荐阅读
- python - 使用 sklearn learn 对列表列表进行矢量化?
- python - 我写了一个简单的石头剪刀布程序,但我想在三个中做到最好,不知道如何将它写到我现有的代码中
- .htaccess - 如何将包含静态和动态变量的 URL 重定向到动态 URL
- laravel - 如何向 laravel-passport 访问令牌添加自定义声明?
- graphite - Graphite django-admin.py raise ImproperlyConfigured("SECRET_KEY 设置不能为空或没有名为 'graphite' 的模块
- java - 首次启动时将活动设为默认活动
- apache-kafka - 具有单个 Kafka 消费者的负载平衡节点 js 应用程序
- javascript - 如何在 Angular Universal 中降低服务器端渲染的成本
- python - 如何提取两个角色之间的兴趣值?
- javascript - 将图像移动到图像集的右侧或左侧 onClick