【发布时间】:2018-07-27 19:36:07
【问题描述】:
我有以下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 |
我想创建一个视图或查询,以使结果看起来像这样。
该表将显示每天和每个type 的t_qty、% of total Qty 和weighted fee:
% 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 中执行此操作,但数据集太大而无法处理。
【问题讨论】:
-
我不知道
weighted fee是怎么计算出来的。 -
@GordonLinoff 我认为
cost列是fee列。我猜提问者写错字了 -
weighted fee=fee*% of total Qty
标签: sql postgresql aggregate-functions