如何从日期范围中选择数据源

时间:2012-05-02 18:54:03

标签: sql postgresql

如果没有创建包含日期范围的所有值的表格,我将如何从数据范围中选择数据源。

我想要完成的是创建在同一周内从单独的表创建的所有项目的总计,同时显示0周新的

示例表:

items
-----------------------------
created_on | name     | type 
-----------------------------
2012-01-01 | Cards    | 1
2012-01-09 | Red Pen  | 2
2012-01-31 | Pencil   | 2
2012-02-01 | Blue Pen | 2

types
--------------
name     | id 
--------------
Fun      | 1
Writing  | 2

示例输出:

----------------------------
year | week | fun | writing 
----------------------------
2012 | 1    | 1   | 0
2012 | 2    | 0   | 1
2012 | 3    | 0   | 0
2012 | 4    | 0   | 0
2012 | 5    | 0   | 2

2 个答案:

答案 0 :(得分:2)

您可以为周数生成一个数字系列

SELECT
  w.week
FROM
  (SELECT generate_series(1,52) as week) as w

实施例

SELECT
  w.year,
  w.week,
  COUNT(i1) as fun,
  COUNT(i2) as writing
FROM (SELECT 2012 as year, generate_series(1,6) as week) as w
LEFT JOIN items i1 ON i1.type = 1 AND w.week = EXTRACT(WEEK FROM i1.created_on)
LEFT JOIN items i2 ON i2.type = 2 AND w.week = EXTRACT(WEEK FROM i2.created_on)
GROUP BY 
  w.year,
  w.week
ORDER BY
  w.year,
  w.week

答案 1 :(得分:0)

非常接近erikxiv,但是你让我朝着正确的方向前进。我有多个表需要从中获取信息,这是选择字段中的附加选择。

select 
    date_year.num,
    date_week.num,
    (   select count(*) from items x
        and EXTRACT(YEAR FROM x.created_on) = date_year.num
        and EXTRACT(WEEK FROM x.created_on) = date_week.num
    ) as item_count
from
    (SELECT generate_series(2011, date_part('year', CURRENT_DATE)::INTEGER) as num) as date_year,
    (SELECT generate_series(1,52) as num) as date_week
where
    (
        date_year.num < EXTRACT (YEAR FROM CURRENT_DATE) 
        OR 
        (
            date_year.num = EXTRACT (YEAR FROM CURRENT_DATE) AND
            date_week.num <= EXTRACT (WEEK FROM CURRENT_DATE)
        )
    )