从postgresql中的select distinct查询插入表中

时间:2017-01-05 13:52:18

标签: postgresql

我有一个包含33列的表,其中有几个重复项,因此我尝试以这种方式删除所有重复项,因为此选择不同的查询具有正确的数据数。

    CREATE TABLE students (
school char(2),sex char(1),age int,address char(1),famsize char(3),
Pstatus char(1),Medu int,Fedu int,Mjob varchar,Fjob varchar,reason varchar,
guardian varchar,traveltime int,studytime int,failures char(1),
schoolsup varchar,famsup varchar,paid varchar,activities varchar,
nursery varchar,higher varchar,internet varchar,romantic varchar,
famrel int,freetime int,goout int,Dalc int,Walc int,
health int,absences int,id serial primary key)

我想从这个select distinct查询中插入所有值 将8列放入不同的空表中。

SELECT DISTINCT ("school","sex","age","address","famsize","Pstatus","Medu","Fedu","Mjob","Fjob","reason","nursery","internet")
FROM students;

2 个答案:

答案 0 :(得分:3)

  

我想将此选择不同查询中包含8列的所有值插入到不同的空表中。

如果要创建表格,请使用create table .. as select ...

create table new_table
as
SELECT DISTINCT school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet
FROM students;

其他方面只需使用基于select的插入:

insert into empty_table (school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet)
SELECT DISTINCT school, sex, age, address, famsize, "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", reason, nursery, internet
FROM students;

非常重要:在选择列表中的列周围添加括号 - 这会创建一个带有匿名记录类型的单个列。

答案 1 :(得分:1)

insert into destinationTable(dC1, dC2, dC3, dC4, dC5, dC6, dC7, dC8)
select sC1, sC2, sC3, sC4, sC5, sC6, sC7, sC8
from sourceTable

您可以join table来获取33 column