sql - 按 3 个字段分组时显示聚合数据的单个 SQL 查询

标签 sql postgresql group-by aggregate

我有一个包含基本信息的表格:

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 查询(每个人-团队-国家有一条记录)来显示以下数据。请注意,我希望它按 nameIdteamIdcountryId

分组
  • 姓名、团队和国家
  • 目标/出局率(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/

相关文章:

php - 使用 PHP 获取 MYSQL 数据库表中的最后一个条目

sql - 从 SQL Server 中的文本中提取数字

sql - 使用 Left Join 时避免在 GROUP BY 子句中指定每个表字段

MYSQL 关系查询问题

ruby-on-rails - rails : Postgres + rake db:structure:dump using wrong user

postgresql - 如何禁用 postgres 中的 super 用户

c# - PostgreSQL、Linq C# 错误 'could not determine data type of parameter $1'

sql - oracle中的group by和union

sql - 按多列分组的聚合函数

c# - 为不同的数据库转换 SQL 查询