SQL总计和加权平均值的百分比

时间:2018-07-27 19:36:07

标签: sql postgresql aggregate-functions

我有以下postgreSql表stock,其结构如下:

| column |  pk |
+--------+-----+
| date   | yes |
| id     | yes |
| type   | yes |
| qty    |     |
| fee    |     |

该表如下所示:

|    date    |  id | type | qty  | cost |
+------------+-----+------+------+------+
| 2015-01-01 | 001 | CB04 |  500 |    2 |
| 2015-01-01 | 002 | CB04 | 1500 |    3 |
| 2015-01-01 | 003 | CB04 |  500 |    1 |
| 2015-01-01 | 004 | CB04 |  100 |    5 |
| 2015-01-01 | 001 | CB02 |  800 |    6 |
| 2015-01-02 | 002 | CB03 | 3100 |    1 |

我想创建一个视图或查询,以便结果看起来像这样。 该表将分别显示每天t_qty% of total Qty的{​​{1}},weighted feetype

% of total Qty = qty / t_qty weighted fee = fee * % of total Qty

|    date    |  id | type | qty  | cost | t_qty | % of total Qty | weighted fee |
+------------+-----+------+------+------+-------+----------------+--------------+
| 2015-01-01 | 001 | CB04 |  500 |    2 |  2600 |           0.19 |         0.38 |
| 2015-01-01 | 002 | CB04 | 1500 |    3 |  2600 |           0.58 |         1.73 |
| 2015-01-01 | 003 | CB04 |  500 |    1 |  2600 |           0.19 |        0.192 |
| 2015-01-01 | 004 | CB04 |  100 |    5 |  2600 |           0.04 |        0.192 |
|            |     |      |      |      |       |                |              |

我可以在Excel中执行此操作,但是数据集太大而无法处理。

1 个答案:

答案 0 :(得分:1)

您可以将SUM windows函数结合使用,并进行一些计算。

SELECT *,
       SUM(qty) OVER (PARTITION BY date ORDER BY date) t_qty,
       qty::numeric/SUM(qty) OVER (PARTITION BY date ORDER BY date) ,
       fee * (qty::numeric/SUM(qty) OVER (PARTITION BY date ORDER BY date))
FROM T 

如果您想Rounding,可以使用ROUND函数。

SELECT *,
       SUM(qty) OVER (PARTITION BY date ORDER BY date) t_qty,
       ROUND(qty::numeric/SUM(qty) OVER (PARTITION BY date ORDER BY date),3) "% of total Qty",
       ROUND(fee * (qty::numeric/SUM(qty) OVER (PARTITION BY date ORDER BY date)),3) "weighted fee"
FROM T 

sqlfiddle

[结果]

|       date |  id | type |  qty | fee | t_qty | % of total Qty | weighted fee |
|------------|-----|------|------|-----|-------|----------------|--------------|
| 2015-01-01 | 001 | CB04 |  500 |   2 |  2600 |          0.192 |        0.385 |
| 2015-01-01 | 002 | CB04 | 1500 |   3 |  2600 |          0.577 |        1.731 |
| 2015-01-01 | 003 | CB04 |  500 |   1 |  2600 |          0.192 |        0.192 |
| 2015-01-01 | 004 | CB04 |  100 |   5 |  2600 |          0.038 |        0.192 |
| 2015-01-02 | 002 | CB03 | 3100 |   1 |  3100 |              1 |            1 |