计算每月收入的百分比

时间:2016-02-04 13:36:09

标签: sql sql-server sql-server-2012 sum percentage

我有以下基础数据:

+-------+-------+---------------+
| Order | Month | sqft produced |
+-------+-------+---------------+
|  1001 |     4 | 10.29         |
|  1001 |     6 | 4'367.66      |
|  1001 |     7 | 203.57        |
|  1001 |     8 | 294.61        |
|  1001 |     9 | 92.28         |
|  1001 |    10 | 34.47         |
|  1001 |    12 | 16.59         |
|  1002 |     1 | 1.74          |
|  1002 |     4 | 19.54         |
|  1002 |     7 | 5'552.21      |
|  1002 |     9 | 309.62        |
|  1002 |    10 | 24.15         |
|  1002 |    12 | 52.16         |
|  1003 |     5 | 807.45        |
+-------+-------+---------------+

这是三个订单,我想根据每月产生的平方英尺的百分比来分配收入。

收入表:

+-------+-----------+
| Order |  Revenue  |
+-------+-----------+
|  1001 | 1'135'465 |
|  1002 | 1'773'499 |
|  1003 | 172'633   |
+-------+-----------+

因此查询的输出应如下所示:

+-------+-------+------------------+
| Order | Month | Revenue produced |
+-------+-------+------------------+
|  1001 |     4 | 2'327.72         |
|  1001 |     6 | 988'017.67       |
|  1001 |     7 | 46'050.00        |
|  1001 |     8 | 66'644.36        |
|  1001 |     9 | 20'874.86        |
|  1001 |    10 | 7'797.53         |
|  1001 |    12 | 3'752.86         |
|  1002 |     1 | 517.82           |
|  1002 |     4 | 5'815.02         |
|  1002 |     7 | 1'652'314.97     |
|  1002 |     9 | 92'141.64        |
|  1002 |    10 | 7'186.94         |
|  1002 |    12 | 15'522.60        |
|  1003 |     5 | 172'633.00       |
+-------+-------+------------------+

我正在努力寻找以这种格式获取基础数据的方法,因为我似乎无法按月拆分它。

2 个答案:

答案 0 :(得分:1)

通过将平方英尺数除以[订单]上划分的平方英尺的总和来获得百分比,可以获得您想要的内容:

select p.[Order], 
       [Month], 
       Revenue, 
       [sqft produced], 
       CAST([sqft produced] / SUM([sqft produced]) OVER(PARTITION BY p.[Order]) AS DECIMAL(10,5)) * 100 as sqft_percentage, 
       Revenue * CAST([sqft produced] / SUM([sqft produced]) OVER(PARTITION BY p.[Order]) AS DECIMAL(10,5)) as revenue_produced
FROM [Orders] p
INNER JOIN Revenue r
ON r.[Order] = p.[Order]

答案 1 :(得分:0)

让我们调用第一个表sqft和第二个revenues。为避免保留字,第一个表列的名称将为:

order_id, month_num, sqft_produced

第二个:

order_id, total_revenue

您需要的SQL就是这样的(这是针对Oracle的):

SELECT order_id, month_num, (sqft_produced / total_sqft * total_revenue) revenue_produced
FROM sqft INNER JOIN
(SELECT order_id, total_sqft, total_revenue FROM (
(SELECT order_id, sum(sqft_produced) total_sqft
GROUP BY order_id) sqfts INNER JOIN revenues ON sqfts.order_id = revenues.order_id)) totals
ON sqft.order_id = totals.order_id;

一步一步:

SELECT order_id, sum(sqft_produced) total_sqft
GROUP BY order_id;

这可以获得订单产生的总平方英尺。

(SELECT order_id, sum(sqft_produced) total_sqft
GROUP BY order_id) sqfts INNER JOIN revenues ON sqfts.order_id = revenues.order_id;

这可以为您提供总收入和总平方英尺的表格。

然后你将这个表加入你的sqft表并将每个月产生的平方英尺除以总平方英尺并乘以总收入,从而按比例将收入分成平方英尺。