Table WIDGET
Columns Country, Contract, Price
Table WEIGHT
Columns Contract, Weight
我正在尝试执行 SUMRPRODUCT(Contract, Weight)/SUM(Weight)
但针对 Country
的所有值。我试过的改编自 Weighted average in T-SQL (like Excel's 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
的一个值而不是所有值计算它。我怎样才能得到 DISTINCT(Country)
的列表和旁边过滤后的契约(Contract)的 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
关于mysql - SQL SUMPRODUCT 有一个扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622179/