【问题标题】:Finding previous day of the week查找一周的前一天
【发布时间】:2010-12-21 18:16:45
【问题描述】:

在 PostgreSQL 8.4 中,给定一个日期,如果该日期不是星期五,我想找到上一个星期五的日期。有人可以告诉我是否有内置函数或给出我自己的函数背后的逻辑。

【问题讨论】:

标签: postgresql


【解决方案1】:

试试这个,其他日子也可以,写博客http://www.ienablemuch.com/2010/12/finding-previous-day-of-week.html

create or replace function previous_date_of_day(the_date date, dow int) returns date
as
$$
select
    case when extract(dow from $1) < $2 then
        $1 - ( extract(dow from $1) + (7 - $2) )::int
    else
        $1 - ( extract(dow from $1) - $2)::int
    end;
$$ language 'sql';


select to_char(z.ds, 'Mon dd yyyy dy') as source, 
     to_char( previous_date_of_day(z.ds, 5), 'Mon dd yyyy dy') as dest
from
(
     select 'Dec 1 2010'::date + x.n as ds
     from generate_series(0,17) as x(n)
) as z

【讨论】:

    【解决方案2】:

    你不用case就解决了:

    select 
    the_date 
    from 
    (
      select 
        now()::date - num as the_date, -- generate rows of possible dates
        extract(dow from (now()::date - num)) -- dow for the where condition
      from (select  generate_series(0,6) as num) as t
    ) as days 
    where date_part = 5;
    

    【讨论】:

      【解决方案3】:
      SELECT 
          CASE 
      -- 1. if Friday, return date
          WHEN EXTRACT(DOW FROM my_date) = 5 
          THEN my_date
      -- 2. if Saturday, subtract 1
          WHEN EXTRACT(DOW FROM my_date) = 6 
          THEN my_date - INTERVAL '1 day'
      -- 3. all other days of the week, subtract `DOW + 2` from my_date
          -- should be ELSE for future-proofing ;-) MB
          ELSE -- WHEN EXTRACT(DOW FROM my_date) < 5 THEN
              my_date - ((EXTRACT(DOW FROM my_date) + 2)::TEXT||'days')::INTERVAL
          END AS tgif
      FROM 
          my_table
      WHERE 
          my_date IS NOT NULL
      

      【讨论】:

      • 不错的解决方案。但是,如果需求发生变化,比如星期四,就很难修改该查询。查询应该有更少的幻数,所以很容易修改。如果星期四需要,我制定的查询只需将 5 更改为 4。 2 看起来像一个神奇的数字。但我仍在尝试理解您的查询 ;-) 并尝试周四和其他日子
      • 星期四不适用于该查询,请参阅ienablemuch.com/2010/12/finding-previous-day-of-week.html
      【解决方案4】:
      select case when extract(dow from your_date) < 5 then
              your_date - (extract(dow from your_date) + integer '2')
             else when extract(dow from your_date) > 5 then
              your_date - integer '1' 
             else 
              your_date
             end
      

      参考http://developer.postgresql.org/pgdocs/postgres/functions-datetime.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-28
        • 2012-03-02
        • 2014-03-08
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        相关资源
        最近更新 更多