【问题标题】:SQL percent of total and weighted averageSQL 占总平均值和加权平均值的百分比
【发布时间】: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 |

我想创建一个视图或查询,以使结果看起来像这样。 该表将显示每天和每个typet_qty% of total Qtyweighted 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


【解决方案1】:

您可以将SUMwindows 函数 和一些计算一起使用。

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 |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多