SQL总百分比和加权平均值

问题描述 投票:0回答:1

我有以下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 Qtyweighted 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中执行此操作,但数据集太大而无法处理。

sql postgresql aggregate-functions
1个回答
1
投票

您可以使用带有Windows功能的SUM和一些计算来实现它。

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 |
© www.soinside.com 2019 - 2024. All rights reserved.