繁体   English   中英

SQL SUMPRODUCT有所不同

[英]SQL SUMPRODUCT with a twist

Table WIDGET
    Columns Country, Contract, Price

Table WEIGHT
    Columns Contract, Weight

我正在尝试对Country所有值进行SUMRPRODUCT(Contract, Weight)/SUM(Weight) 我尝试过的是改编自T-SQL中的加权平均值(例如Excel的SUMPRODUCT) ,看起来像

SELECT 
    Country 
    SUM(widget.price * weight.weight) / SUM(weight.weight)
FROM
    Widget
        INNER JOIN
    Weight ON Widget.contract = Weight.contract
WHERE
    Weight.contract >= '2016-01-01'
    AND Weight.contract <= '2016-12-01'

问题在于,它是针对“ Country一个值而不是针对所有Country值进行计算的。 如何获取旁边的DISTINCT(Country)SUMPRODUCT()/SUM()的列表?

样本数据

+-----------+---------+------------+-------+
| widget_id | country | contract   | price |
+-----------+---------+------------+-------+
|         4 | CA      | 2016-01-01 | 16.00 |
|         5 | CA      | 2016-02-01 | 32.00 |
|         6 | CA      | 2016-03-01 | 64.00 |
|         1 | US      | 2016-01-01 | 32.00 |
|         2 | US      | 2016-02-01 | 64.00 |
|         3 | US      | 2016-03-01 | 96.00 |
+-----------+---------+------------+-------+

+-----------+------------+--------+
| weight_id | contract   | weight |
+-----------+------------+--------+
|         1 | 2016-01-01 |      1 |
|         2 | 2016-02-01 |      8 |
|         3 | 2016-03-01 |     64 |
+-----------+------------+--------+

所需的输出

+---------+-----------+
| Country | Wtd Price |
+---------+-----------+
| CA      | 59.835616 |
| US      | 91.616438 |
+---------+-----------+

你应该像这样按国家分组

SELECT 
    Country 
    SUM(widget.price * weight.weight) / SUM(weight.weight)
FROM
    Widget
        INNER JOIN
    Weight ON Widget.contract = Weight.contract
WHERE
    Weight.contract >= '2016-01-01'
    AND Weight.contract <= '2016-12-01'
GROUP BY Country

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM