0

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

我想要完成的是从单独的表中创建在同一周内创建的所有项目的运行总计,同时显示 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
4

2 回答 2

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
于 2012-05-02T19:14:16.980 回答
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)
        )
    )
于 2012-05-02T20:24:18.317 回答