Postgres案例陈述错误

时间:2016-01-22 19:20:54

标签: sql postgresql case

我正在尝试创建一个基于职位发布状态的Postgres案例陈述。例如:

  • status'Closed'时,我希望updated_at时间戳与created_at时间戳之间的天数存在差异。
  • status'Open''Pending'时,我想从当前时间戳中减去created_at时间戳。

我到目前为止创建的查询如下所示:

Select users.first_name || " " || users.last_name,
users.email,
organizations.name,
organizations.vertical,
jobs.name,
jobs.id
(Case
When jobs.status = 'Closed' Then jobs.updated_at - jobs.created_at Else 'Not Closed') END AS days_to_hire,
(Case
When jobs.status IN ('Open,'Pending') Then current_timestamp - jobs.created_at Else 'Closed_or_Deleted') END AS days_open,
FROM organizations
JOIN users on organizations.id = users.organization_id
JOIN jobs on user.id= jobs.user.id

但是,它并不像我预期的那样有效:

  

错误:语法错误位于或附近“)”

我无法找出原因。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

简答

您的查询中有三个语法问题:

  1. 缺少逗号
  2. 在您的CASE对帐单
  3. 中放错了右括号
  4. 第二个CASE声明
  5. 中未终止的字符串文字

    我已在下面注明:

    Select users.first_name || " " || users.last_name,
    users.email,
    organizations.name,
    organizations.vertical,
    jobs.name,
    -- Missing comma added below.
    jobs.id,
    --jobs.id
    -- Closing paren moved to after `END` below.
    (Case
    When jobs.status = 'Closed' Then jobs.updated_at - jobs.created_at Else 'Not Closed' END) AS days_to_hire, 
    --(Case
    --When jobs.status = 'Closed' Then jobs.updated_at - jobs.created_at Else 'Not Closed') END AS days_to_hire,
    -- Closing paren moved to after `END` and a closing single quote added
    -- to terminate the string literal 'Open' below.
    (Case
    When jobs.status IN ('Open','Pending') Then current_timestamp - jobs.created_at Else 'Closed_or_Deleted' END) AS days_open,
    --(Case
    --When jobs.status IN ('Open,'Pending') Then current_timestamp - jobs.created_at Else 'Closed_or_Deleted') END AS days_open,
    FROM organizations
    JOIN users on organizations.id = users.organization_id
    JOIN jobs on user.id= jobs.user.id
    

    附录

    同样,您的查询很难以格式化的方式阅读。这使得调试变得更加困难。

    考虑一种利用缩进和一致关键字大小写的替代方法(即小写与大写):

    SELECT
        users.first_name || " " || users.last_name,
        users.email,
        organizations.name,
        organizations.vertical,
        jobs.name,
        jobs.id,
        (CASE
             WHEN jobs.status = 'Closed' THEN jobs.updated_at - jobs.created_at
             ELSE 'Not Closed'
         END) AS days_to_hire, 
        (CASE
             WHEN jobs.status IN ('Open', 'Pending') THEN CURRENT_TIMESTAMP - jobs.created_at
             ELSE 'Closed_or_Deleted'
         END) AS days_open,
    FROM organizations
    JOIN users ON organizations.id = users.organization_id
    JOIN jobs ON user.id= jobs.user.id
    

    更容易阅读和调试我认为你会同意。

    我个人并不关心CASE语句周围的括号,但与良好,一致地使用缩进和关键词大小相比,这是一个次要的选择。