【发布时间】:2021-04-28 14:11:32
【问题描述】:
我有 2 个表格,一个带有区域、操作和数量,另一个带有价格,目标是将两者结合在一个视图中
表1
areaid integer
bananaunits integer
kilometers_ran integer
dogecoins integer
areaid | bananaunits | kilometers_ran | dogecoin
1 | 0 | 1 | 10
2 | 4 | 2 | 100
表2
rateid integer
description text
cost_per_unit integer
rateid | description | cost_per_unit
1 | price per banana | 0.5
2 | price per kilometers run | 2
3 | price per doge | 1
预期的结果是具有如下字段的视图:
areaid、rateid、描述、cost_per_unit、units、combined_cost
areaid| rateid| description| cost_per_unit| units| total_cost
1 | 1 | price per banana | 0.5 | 0 | 0
1 | 2 | per kilometers run | 2 | 1 | 2
1 | 3 | price per doge | 1 | 10 | 10
2 | 1 | price per banana | 0.5 | 4 | 2
2 | 2 | per kilometers run | 2 | 2 | 4
2 | 3 | price per doge | 1 | 100 | 100
换句话说,我需要在单独的行中显示每个区域的所有费率。如何做到这一点?
编辑:当前查询不起作用
从table1、table2中选择areaid、rateid、description、cost_per_unit、units、combined_cost
【问题讨论】:
-
将列名的一部分移动到行元素和将行元素移动到列名称为透视和反透视。 PS Unpivoted 数据通常是一个糟糕的设计,当你有参数化结构时,参数应该是一列。
-
@philipxy 如果您的意思是将 table1 中的项目作为行移动到输出中,原因很简单,每个项目需要进行更多计算并且项目很多,所以输出否则很容易膨胀到 300 列
-
我说的是 table1 的列名不应该有单元类型,但它应该有 id 和类型的列。 (比如 table2。)但是鉴于你有 table1,找出如何旋转。
-
@philipxy table1 是多个表的聚合表,每列有一个条件,有时依赖于几个表。它的目的是计算每个区域的特征
-
请通过编辑而非 cmets 进行澄清。 PS你的评论更多的是碎片。
标签: sql postgresql join view