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)
和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 |
+---------+-----------+
答案 0 :(得分:2)
你应该按国家分组
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