对不同表中的每一行执行查询

时间:2013-04-04 03:25:00

标签: sql postgresql date timestamp subquery

我有一个临时表,其中包含开始和结束时间的unix时间戳:

create temporary table rr (t timestamp);

insert into rr (t)
    select generate_series(
        (select timestamp 'epoch' + create_dte_timestamp * INTERVAL '1 second'
        from data
        order by create_dte_timestamp asc limit 1),
    current_timestamp, interval '1 day');

create temporary table ts (s numeric(10), e numeric(10));

insert into ts (s, e)
    select date_part('epoch', (to_timestamp(to_char(t, 'MM/DD/YYYY 00:00:00'),   
    'MM/DD/YYYY HH24:MI:SS')) at time zone 'UTC')::int,
    date_part('epoch', (to_timestamp(to_char(t, 'MM/DD/YYYY 23:59:59'),
    'MM/DD/YYYY HH24:MI:SS')) at time zone 'UTC')::int from rr order by t asc;

我想对ts表的每一行执行查询:

select count(id) from data
where create_dte_timestamp >= ts.s and create_dte_timestamp <= ts.e

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我会尝试使用子查询:

select 
  ts.s, ts.e, 
  (select count(id) from data
  where create_dte_timestamp >= ts.s and create_dte_timestamp <= ts.e)
  as c
from ts;