批量插入查询到表(postgresql)

时间:2017-11-12 09:58:13

标签: postgresql postgresql-9.4

我找不到答案:

我想将此查询的结果插入表'days':

WITH days AS ( 
SELECT 
date_part('dow',generate_series('2017-11-01','2017-11-30', interval '1 day')) as dow, 
to_char(generate_series('2017-11-01','2017-11-30', interval '1 day'),'YYYY-MM-DD') as date ) 

SELECT 0 as id,date, 
CASE 
WHEN dow=1 then 8 
WHEN dow=2 then 8 
WHEN dow=3 then 8 
WHEN dow=4 then 8 
WHEN dow=5 then 8 
WHEN dow=6 then 0 
WHEN dow=0 then 0 
ELSE 0 END as wtime 
FROM days

表格就像这样简单:

CREATE TABLE days
    (id serial, dates date, wtime numeric(8,2));

在我的梦中它应该是这样的:

INSERT * INTO days FROM (

WITH days AS ( 
SELECT 
date_part('dow',generate_series('2017-11-01','2017-11-30', interval '1 day')) as dow, 
to_char(generate_series('2017-11-01','2017-11-30', interval '1 day'),'YYYY-MM-DD') as date ) 

SELECT 0 as id,date, 
CASE 
WHEN dow=1 then 8 
WHEN dow=2 then 8 
WHEN dow=3 then 8 
WHEN dow=4 then 8 
WHEN dow=5 then 8 
WHEN dow=6 then 0 
WHEN dow=0 then 0 
ELSE 0 END as wtime 
FROM days)

这可能吗?怎么样?

http://sqlfiddle.com/#!15/91c720/8

2 个答案:

答案 0 :(得分:3)

首先需要CTE(article{ margin:0px auto; display:block; width:80%; float:left; background:red; } ),然后是插入。您还需要为CTE指定一个不同的名称,否则名称WITH将是不明确的

days

但是,当您的查询为with gen_days ( ...) insert into days select * from gen_days; 列生成varchar值而不是真正的date类型时,您会遇到问题。您需要更改它以将DATE的结果转换为日期。您还只需要一个generate_series()而不是两个:

generate_series()

无关,但是:你真的不需要CTE。您可以将插入简化为:

WITH gen_dates AS ( 
 SELECT date_part('dow',d.dt) as dow, 
        dt::date as date
  from generate_series('2017-11-01','2017-11-30', interval '1 day') as d(dt)
) 
insert into days (dates, wtime)
SELECT date, 
       CASE 
         WHEN dow=1 then 8 
         WHEN dow=2 then 8 
         WHEN dow=3 then 8 
         WHEN dow=4 then 8 
         WHEN dow=5 then 8 
         WHEN dow=6 then 0 
         WHEN dow=0 then 0 
         ELSE 0
       END as wtime 
FROM gen_dates

请注意insert into days (dates, wtime) SELECT dt::date, CASE date_part('dow', dt) WHEN 1 then 8 WHEN 2 then 8 WHEN 3 then 8 WHEN 4 then 8 WHEN 5 then 8 WHEN 6 then 0 WHEN 0 then 0 ELSE 0 END as wtime FROM generate_series('2017-11-01','2017-11-30', interval '1 day') as d(dt); 语句的简写形式,您不必重复测试的表达式。

答案 1 :(得分:0)

也许您的问题是CTE和您的目标表具有相同的名称。 另一个问题是你的日期"源列不是真正的date数据类型:

INSERT * INTO days
WITH days_cte AS ( 
SELECT 
date_part('dow',generate_series('2017-11-01','2017-11-30', interval '1                     day')) as dow, 
to_char(generate_series('2017-11-01','2017-11-30', interval '1 day'),'YYYY-MM-DD') as date ) 
SELECT 0 as id, "date"::date, 
CASE 
WHEN dow=1 then 8 
WHEN dow=2 then 8 
WHEN dow=3 then 8 
WHEN dow=4 then 8 
WHEN dow=5 then 8 
WHEN dow=6 then 0 
WHEN dow=0 then 0 
ELSE 0 END as wtime 
FROM days_cte