根据其他列PSQL的值在SELECT语句中添加其他列

时间:2016-02-25 13:55:27

标签: sql postgresql select aggregate-functions psql

我有一张每人的驾驶执照表,知道一个人何时获得了驾照。驾驶执照的有效期可以是您获得驾驶执照之日起的X天或特定日期。

 acquired        relative      specific_date      valid_type     expiration_date
----------------------------------------------------------------------------------
2015-02-05         500             null              days
2015-02-05         null         2016-03-05           date
2015-02-05         200             null              days
2015-02-05         null         2016-02-22           date

我现在的查询是:

SELECT acquired,
       relative_date,
       specific_date,
       valid_type
FROM person_drivers_license
WHERE (valid_type = 'days'
       AND (EXTRACT(epoch
                    FROM acquired) - EXTRACT(epoch
                                             FROM now()))/86400 + relative_date > 0)
  OR (valid_type = 'DATE'
      AND specific_date >= now()));

我正在尝试使用上面的select语句添加expiration_date列。如果是特定日期,只需取日期并将其置于expiration_date中,如果是相对日期,则在获取日期的帮助下计算到期日期。这在PSQL中是否可行?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT acquired,
       relative_date,
       specific_date,
       valid_type
       CASE valid_type
         WHEN 'days' THEN acquired + relative_date
         WHEN 'date' THEN specific_date
         ELSE NULL
       END AS expiration_date
FROM   person_drivers_license;

答案 1 :(得分:1)

首先 - 在postgres中有一种更简单的日期数学方法。你可以使用类似的东西:

acquired + relative_date * interval '1 day' >= current_date

acquired + relative_date >= current_date 
-- any integer can be treated as interval in days for date mathematics is SQL

对于这个问题 - 试试其中一个:

CASE WHEN valid_type = 'days' 
     THEN acquired + relative_date * interval '1 day'
     WHEN valid_type = 'date'
     THEN specific_date
     --ELSE ??? you may specify something here
END

COALESCE(specific_date, acquired + relative_date * interval '1 day')

查询可能如下所示:

SELECT acquired,
       relative_date,
       specific_date,
       valid_type,
       COALESCE(specific_date, acquired + relative_date * interval '1 day') as valid_date
FROM person_drivers_license
WHERE COALESCE(specific_date, acquired + relative_date * interval '1 day') >= current_date

答案 2 :(得分:0)

你不需要pl / sql

SELECT acquired,
       relative_date,
       specific_date,
       valid_type,
       CASE WHEN specific date = "date" -- starts here
       THEN specific date 
       ELSE acquired + cast('1 months' as interval)END 
       AS expiration_date -- end here
FROM person_drivers_license
WHERE (valid_type = 'days'
       AND (EXTRACT(epoch
                    FROM acquired) - EXTRACT(epoch
                                             FROM now()))/86400 + relative_date > 0)
  OR (valid_type = 'DATE'
      AND specific_date >= now()));