如何获得每月/每季度的销售百分比

时间:2015-06-11 02:48:21

标签: sql sql-server oracle

我有一份月销售表

Quarter Month Monthly Sales
1       Jan   586
1       Feb   204
1       Mar   465
2       Apr   684
2       May   756
2       Jun   97

现在我想要一个结果

Quarter Month Monthly Sales Total Sales% Quarterly Sales%
1       Jan    586           20.98%         45.25%
1       Feb    204           7.30%          16.25%
1       Mar    465           16.65%         37.05%
2       Apr    684           24.49%         44.50%
2       May    756           27.07%         49.18%
2       Jun    97            3.47           6.31%

总销售额%=每月销售额/总和(每月销售额) 季度销售额%=每月销售额/季度销售额

如何在SQL中获取此输出?

2 个答案:

答案 0 :(得分:1)

使用centerNode

CROSS APPLY

答案 1 :(得分:1)

如果您使用的是Oracle,则应使用ratio_to_report分析函数。 (http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

select quarter,
       month,
       monthly_sales,
       round(ratio_to_report(monthly_sales) over() * 100, 2) as total_sales_pct,
       round(ratio_to_report(monthly_sales) over(partition by quarter) * 100, 2) as qtr_sales_pct
  from monthly_sales;

小提琴: http://sqlfiddle.com/#!4/71aeb7/1/0

以上假设您只选择一年的数据,因为分析函数将解释给定的结果集。如果您的查询跨越多年,则需要按实际表中年份的任何列进行额外分区。

相关问题