Sql 按时段划分月份

Sql 按时段划分月份,sql,postgresql,row-number,Sql,Postgresql,Row Number,假设我有两年的数据。从2010年1月到2011年12月。 我想把每个月都归类为周期。所以2010年1月是我的1日,2010年2月是我的2日,依此类推,直到2011年12月是我的24个月 我知道我可以这样做: select year,mn, case when year=2010 and mn=01 then 1 else when year=2010 and mn=02 then 2 else when year=2010 and mn=03 then 3

假设我有两年的数据。从2010年1月到2011年12月。
我想把每个月都归类为周期。所以2010年1月是我的1日,2010年2月是我的2日,依此类推,直到2011年12月是我的24个月

我知道我可以这样做:

select 
    year,mn, 
    case when year=2010 and mn=01 then 1
    else when year=2010 and mn=02 then 2
    else when year=2010 and mn=03 then 3
    //and so on until // else when year=2011 and mn=12 then 24 end 
from mytable;
结果是:

year    mn  period
2010    1   1
2010    2   2
2010    3   3
2010    4   4
2010    5   5
2010    6   6
2010    7   7
2010    8   8
2010    9   9
2010    10  10
2010    11  11
2010    12  12
2011    1   13
2011    2   14
2011    3   15
2011    4   16
2011    5   17
2011    6   18
2011    7   19
2011    8   20
2011    9   21
2011    10  22
2011    11  23
2011    12  24

我想避免这种冗长而不明智的方法。

针对这种特殊情况的廉价版本:

select
    year, mn,
    row_number() over (order by year, mn) as period
from t
SELECT year, mn, (year - 2010) * 12 + mn AS period
FROM   tbl;
这也可以解释您的数据中可能缺少的月份。

即使只选择一些行,它也会给您提供一致的数字。

不需要花哨的窗口功能。只要用简单的方法就行了。对于给定的
{epoch year}
{epoch month}
(例如,分别为2010和1),公式

( ( 12*year + mn ) - ( 12*{epoch-year} + {epoch-month} )
将以月份为单位给出从历元开始的偏移量。再加上1,你就有了你的周期号。这会让你想到这样的事情:

select year ,
       mn   ,
       (   ( 12*year         + mn            )
         - ( 12*{epoch-year} + {epoch-month} )
       ) + 1 as period
       ...
from some-table
where   year > {epoch-year}
   OR ( year = {epoch-year} and mn >= {epoch-month} )
select t.year ,
       t.mn   ,
       (   ( 12*year       + mn          )
         - ( 12*epoch.year + epoch.month )
       ) + 1 as period
       ...

from       ( select year,mn
             from some-table
             order by year , mn
             limit 1
           ) epoch
cross join some-table t
如果你心中没有特定的时代,你可以这样做:

select year ,
       mn   ,
       (   ( 12*year         + mn            )
         - ( 12*{epoch-year} + {epoch-month} )
       ) + 1 as period
       ...
from some-table
where   year > {epoch-year}
   OR ( year = {epoch-year} and mn >= {epoch-month} )
select t.year ,
       t.mn   ,
       (   ( 12*year       + mn          )
         - ( 12*epoch.year + epoch.month )
       ) + 1 as period
       ...

from       ( select year,mn
             from some-table
             order by year , mn
             limit 1
           ) epoch
cross join some-table t
您应该注意,可以根据超过1个月的周期长度来计算周期数的公式:只需计算以月为单位的偏移量,然后使用整数除法将该偏移量除以以月为单位的周期长度,从而得到连续的周期数,如

       (   ( 12*year + mn )
         - ( 12*2010 + 1  )
       ) DIV 3 + 1 as period
应该给你3个月的时间