WHERE子句postgres中的SELECT问题

时间:2018-09-11 17:25:11

标签: sql postgresql

我正在尝试使用以下命令创建表:

SELECT
    data_req,
    count(servico) as qtdeServico,
    count(metodo) as qtdeMetodo,
    consumerid,
    metodo,
    status_metodo,
    servico,
    sum(tempo_req)
INTO
    consolidado
FROM 
    requisicoes AS r
WHERE 
    r.data_req > SELECT MAX(c.data_req) FROM consolidado c  
GROUP BY 
    data_req, consumerid, metodo, status_metodo, servico;

不幸的是,我在where的select子句中遇到错误。我正在使用postgres。

有什么建议吗?预先感谢。

4 个答案:

答案 0 :(得分:1)

您的查询具有许多特质。以下是更正确的语法:

create table consolidado as 
    select data_req, count(servico) as qtdeServico, count(metodo) as qtdeMetodo,
           consumerid, metodo, status_metodo, servico,
           sum(tempo_req) as sum_tempo_req
    from requisicoes r
    where r.data_req > (select max(c.data_req) from consolidado c) 
    group by data_req, consumerid, metodo, status_metodo, servico;

这可以修复以下错误:

  • Postgres建议使用CREATE TABLE AS胜过SELECT INTO(请参阅here)。
  • 创建表时应命名所有列。
  • 您需要在子查询周围添加括号。

但是,查询没有意义。它正在创建一个名为consolidado的表并从该表中读取。从逻辑上讲这很麻烦。另外,qtMetodoqtdeServico通常具有相同的值-它们位于GROUP BY列中,这意味着它们被组分隔。

答案 1 :(得分:0)

请尝试在SELECT句子周围加上“(.....)”:

SELECT
    data_req,
    count(servico) as qtdeServico,
    count(metodo) as qtdeMetodo,
    consumerid,
    metodo,
    status_metodo,
    servico,
    sum(tempo_req)
    into consolidado
    FROM requisicoes as r
    WHERE 
    r.data_req > (select max(c.data_req) from consolidado c  
    GROUP BY data_req, consumerid, metodo, status_metodo, servico);

答案 2 :(得分:0)

假设consolidado已经存在。.您将需要使用INSERT INTO ()... SELECT语法。子查询也应放在括号内:

INSERT INTO consolidado (data_req, qtdeServico.. rest of cols)
SELECT
    data_req,
    count(servico) as qtdeServico,
    count(metodo) as qtdeMetodo,
    consumerid,
    metodo,
    status_metodo,
    servico,
    sum(tempo_req)
FROM requisicoes as r
WHERE r.data_req > (select max(c.data_req) from consolidado c)
GROUP BY data_req, consumerid, metodo, status_metodo, servico;

答案 3 :(得分:0)

除了其他人关于CREATE TABLE AS vs SELECT INTO的观点外,我会高度推荐他们结帐CREATE MATERIALIZED VIEW,听起来像是您想要的更多东西。