我想從一個表中選擇所有行並將它們插入到只有所有行上的最大值和最小值的另一行中。不知道如何寫這個沒有group by子句。它的一大桌左右(更新設置=從(選擇最多...)?)是減緩Postgres用最大最小值插入所有行
表1:
id,values
1,2
2,4
3,1
表2:
id,max,min
1,4,1
2,4,1
3,4,1
我想從一個表中選擇所有行並將它們插入到只有所有行上的最大值和最小值的另一行中。不知道如何寫這個沒有group by子句。它的一大桌左右(更新設置=從(選擇最多...)?)是減緩Postgres用最大最小值插入所有行
表1:
id,values
1,2
2,4
3,1
表2:
id,max,min
1,4,1
2,4,1
3,4,1
這將做到這一點:
SELECT n1.id,
n2.mymax,
n2.mymin
FROM
(SELECT MIN(values) AS mymin,
MAX(values) AS mymax
FROM dbTable) n2,
dbTable n1;
SQL小提琴here:
這裏另一個嘗試使用窗口函數(SQLFiddle:http://sqlfiddle.com/#!15/2978e) 這是select來獲取您的數據。
select
id,
min(values) over() as min,
max(values) over() as max
from Table1
要插入這些值中的一個必須執行此SQL
insert into table2 (id, min, max)
select
id,
min(values) over() as min,
max(values) over() as max
from Table1
或從SQL創建 table2中
create table table2 as
select
id,
min(values) over() as min,
max(values) over() as max
from Table1