【发布时间】:2012-06-04 00:05:50
【问题描述】:
当基表日期为 date 或 timestamp 时,许多查询是按周、月或季度进行的。
一般来说,在group by 查询中,是否使用
- 日期功能
- 已预先计算提取的day 表
注意:与DATE lookup table (1990/01/01:2041/12/31)类似的问题
例如,postgresql
create table sale(
tran_id serial primary key,
tran_dt date not null default current_date,
sale_amt decimal(8,2) not null,
...
);
create table days(
day date primary key,
week date not null,
month date not null,
quarter date non null
);
-- week query 1: group using funcs
select
date_trunc('week',tran_dt)::date - 1 as week,
count(1) as sale_ct,
sum(sale_amt) as sale_amt
from sale
where date_trunc('week',tran_dt)::date - 1 between '2012-1-1' and '2011-12-31'
group by date_trunc('week',tran_dt)::date - 1
order by 1;
-- query 2: group using days
select
days.week,
count(1) as sale_ct,
sum(sale_amt) as sale_amt
from sale
join days on( days.day = sale.tran_dt )
where week between '2011-1-1'::date and '2011-12-31'::date
group by week
order by week;
对我来说,date_trunc() 函数似乎更有机,days 表更易于使用。
这里有什么比口味更重要的吗?
【问题讨论】:
-
您可以在表达式
date_trunc('week',tran_dt)::date上创建索引以加快处理速度。
标签: sql postgresql datetime