我有一个包含基本信息的表格:
CREATE TABLE testing.testtable
(
recordId serial NOT NULL,
nameId integer,
teamId integer,
countryId integer,
goals integer,
outs integer,
assists integer,
win integer,
sys_time timestamp with time zone NOT NULL DEFAULT now(),
CONSTRAINT testtable_pkey PRIMARY KEY (recordid)
)
我想要一个 SQL 查询(每个人-团队-国家有一条记录)来显示以下数据。请注意,我希望它按 nameId
、teamId
和 countryId
- 姓名、团队和国家
- 目标/出局率
(G/O)
- 进球+助攻/出局率
(GA/O)
- 胜率
(Win%)
- 当前目标/失败率与一个月前的差异
(rDif)
- 当前目标+助攻/出局率与一个月前的差异
(fDif)
- 当前赢率与一个月前的差异
(winDif)
包含所有记录的示例表:
Id nameId teamId countryId goals outs assists win sys_time
1 1 3 5 2 4 11 1 2013-01-01
2 1 3 5 9 4 19 1 2013-01-01
3 1 3 4 10 2 1 0 2013-01-01
4 1 3 4 11 50 14 1 2013-01-01
5 2 2 2 10 5 4 1 2013-01-01
6 2 3 5 4 7 15 0 2013-01-01
7 1 3 5 4 8 22 0 2014-07-01
8 1 3 4 11 3 5 1 2014-07-01
9 3 1 4 44 1 4 1 2014-07-01
示例所需的输出记录 (1-3-5):
nameId teamId countryId G/O GA/O Win% rDif fDif winDif
1 3 5 0.938 4.19 66 0.44 0.94 -0.34
这些比率很容易检索。对于差异,我做了以下操作:
select tt.nameid
avg(tt.goals) - avg(case when tt.sys_time < date_trunc('day', NOW() - interval '1 month') then tt.goals end) as change
from testing.testtable tt
group by tt.nameid
order by change desc
如果我只想要 nameIds 的差异,这会起作用。但我希望它为名称-团队-国家/地区的每个组合拉出一条记录。我似乎无法正常工作。
最佳答案
您可以按多个字段分组:
select tt.nameid, tt.teamID, tt.countryID,
avg(tt.goals) - avg(case when tt.sys_time < date_trunc('day', NOW() - interval '1 month') then tt.goals end) as change
from testing.testtable tt
group by tt.nameid, tt.teamID, tt.countryID
order by change desc
关于sql - 按 3 个字段分组时显示聚合数据的单个 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537167/