我有一个能够以某种方式(不是熟悉的)聚合表格的练习,我尝试使用分组,总和,最大,最小的函数,但我找不到合并所有的逻辑: 举个例子如下:
db=# select * from test;
id | t1 | t2 | a | b | c
----+----+----+---+---+----
1 | 1 | 2 | x | y | 2
2 | 1 | 2 | y | x | 4
3 | 2 | 3 | x | y | 6
4 | 2 | 4 | y | x | 8
5 | 3 | 4 | x | x | 10
6 | 4 | 5 | x | x | 12
7 | 4 | 7 | x | x | 14
练习是使用以下规则创建表test2:
输出test2将从测试中选择,如下所示
db=# select * from test2;
id | t1 | t2 | a | b | c
----+----+----+---+---+----
1 | 1 | 3 | x | y | 6
2 | 1 | 4 | y | x | 12
5 | 3 | 7 | x | x | 36
作为参考,该表创建如下:
create table test (id BIGSERIAL PRIMARY KEY,t1 int4,t2 int4, a text, b text ,c INT64_UNSIGNED);
insert into test values (1,1,2,'x','y',2);
insert into test values (2,1,2,'y','x',4);
insert into test values (3,2,3,'x','y',6);
insert into test values (4,2,4,'y','x',8);
insert into test values (5,3,4,'x','x',10);
insert into test values (6,4,5,'x','x',12);
insert into test values (7,4,7,'x','x',140;
在SQL server中创建表 -
CREATE TABLE [dbo].[test](
[id] [int] NULL,
[t1] [int] NULL,
[t2] [int] NULL,
[a] [varchar](50) NULL,
[b] [varchar](50) NULL,
[c] [int] NULL
) ON [PRIMARY]
答案 0 :(得分:1)
这是您的查询
适合运动的解决方案
select MIN(id) as id,
MIN(t1) as t1,
Max(t2) as t2,
a,
b,
sum(c) as c
from dbo.test
group by a,b order by id