【发布时间】:2014-07-02 17:13:14
【问题描述】:
我有一张包含基本信息的表格:
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 的差异,这很有效。但我希望它为名称-团队-国家/地区的每种组合创造一个记录。我似乎无法让它工作。
【问题讨论】:
-
您应该可以添加到分组中,所以
group by tt.nameid, tt.teamid, tt.countryid您尝试过吗? (也将它们添加到选择中)或者我在这里缺少什么? -
在您的 select 和 group by 语句中包含额外的列(team_id 和 countryID)
标签: sql postgresql group-by aggregate