【发布时间】:2020-09-18 08:28:25
【问题描述】:
我对 SQL 查询有疑问
我有类似的表
表 1:
id_table1 ean date_from date_to type region town_id consumption
1 1234 2020-01-01 2021-01-01 blue big 100 20000
2 5678 2020-01-01 2021-01-01 blue big2 200 80000
2 6845 2020-01-01 2021-01-01 white small 300 10000
表 2:
id_table2 day type_blue_big_coefficient type_blue_big2_coefficient type_white_coefficient
1 2020-01-01 0.011120 0.32652 0.054165
2 2020-01-01 0.023265 0.12543 0.054165
表 3:
id_table3 day town_id_100_coefficent town_id_200_coefficent
1 2020-01-01 0.011120 0.98556
2 2020-01-01 0.023265 0.58467
我需要像这样显示输出:
EAN Day consumption
1234 2020-01-01 222.4
5678 2020-01-01 26 121.6
6845 2020-01-01 541.65
输出消耗是通过将表 2 中的系数与表 3 中的系数相乘,然后乘以系数 * 表 1 消耗来计算的。
如何正确连接这 3 个表? 如果我将表 3 加入表 1 date_from 和 date_to 我会得到不好的结果(比可能大得多)
【问题讨论】:
-
表之间是什么关系?
-
请使用架构和示例数据创建fiddle
-
将表 2 和 3 标准化为
(id, day, attribute, coeff)。 -
table1中的date_from、date_to的值是否总是相等的?如果不是,那么必须取表 2 和表 3 中的哪些行? -
table1 date_from 和 date_to 表示连接天数。 table2 和 table3 是表 2 和表 3 中这些天的系数,取表 1 date_from 到 date_to 上连接的系数行