date
当基表日期为或时,许多查询是按周、月或季度进行的timestamp
。
通常,在group by
查询中,是否使用 - 日期函数 -day
预先计算了提取的表
注意:与DATE 查找表类似的问题 (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
表格更易于使用。
这里有什么比口味更重要的吗?