我有一个如下所示的架构,我想运行一个查询,在输出中为每一行获取一列points
table.
所以对于每个usage
我想乘以行amount
使用次数的amount
对于引用的points_id
,然后总结并按人分组。因此,对于示例数据,我希望输出如下所示:
Name | foo | bar | baz
-------|------|------|------
Scott | 10.0 | 24.0 | 0.0
Sam | 0.0 | 0.0 | 46.2
这是架构/数据:
CREATE TABLE points (
ident int primary key NOT NULL,
abbrev VARCHAR NOT NULL,
amount real NOT NULL
);
CREATE TABLE usage (
ident int primary key NOT NULL,
name VARCHAR NOT NULL,
points_id integer references points (ident),
amount real
);
INSERT INTO points (ident, abbrev, amount) VALUES
(1, 'foo', 1.0),
(2, 'bar', 2.0),
(3, 'baz', 3.0);
INSERT INTO usage (ident, name, points_id, amount) VALUES
(1, 'Scott', 1, 10),
(2, 'Scott', 2, 12),
(3, 'Sam', 3, 3.4),
(4, 'Sam', 3, 12);
我正在使用 PostgreSQL 9.2.8
数据只是样本。真实的有几千行usage
桌子上可能有十几个points
桌子。这里的真正意图是我不想硬编码所有points
我在许多函数中使用它们时求和。