确定一个月是否包含条目

时间:2010-03-23 14:14:55

标签: sql datetime postgresql timestamp

我有一个带时间戳记的日志列表,我想要一个查询来返回12个布尔人,说明某个月是否包含任何日志,一年中的每个月(从1月开始),即:

(True, False, False, True, False ..., True)

我目前有以下查询,它会显示包含数据的所有月份:

SELECT DISTINCT(EXTRACT(MONTH FROM logdate)) AS month
FROM mytable
WHERE EXTRACT(YEAR FROM logdate) = '2009'
ORDER BY month;

其输出是包含数据的月份列表,例如:

(1, 2, 5, 6, 12)

我无法完成下一步 - 任何指针都会受到赞赏。

我正在使用PostgreSQL v8.4.2。感谢。

3 个答案:

答案 0 :(得分:2)

使用generate_series():

SELECT
    CASE
        WHEN EXTRACT(MONTH FROM logdate) IS NULL THEN false
        ELSE true
    END,
    y AS month
FROM
    mytable RIGHT JOIN generate_series(1,12) AS x(y) ON EXTRACT(month FROM logdate) = y
WHERE 
    EXTRACT(YEAR FROM logdate) = '2009';

答案 1 :(得分:1)

将WHERE移动到JOIN条件:

SELECT DISTINCT
    CASE
        WHEN EXTRACT(MONTH FROM logdate) IS  NULL THEN false
        ELSE true
    END,
    y AS month
FROM
    mytable 
        RIGHT JOIN 
        (SELECT generate_series(1,12)) AS x(y) ON ((EXTRACT(MONTH FROM logdate)) = y AND EXTRACT(YEAR FROM logdate) = '2009')
ORDER BY 
    month ASC;

年份条件仅适用于匹配记录。

答案 2 :(得分:0)

我不确定,如果这是最优雅的解决方案,但它应该有效(在Postgres上测试):

SELECT (CASE WHEN max(sub.jan)=1 THEN true ELSE false END) AS jan,
       (CASE WHEN max(sub.feb)=1 THEN true ELSE false END) AS feb,
       ...
FROM
(
    SELECT (CASE WHEN (EXTRACT(MONTH FROM logdate))=1 THEN 1 ELSE 0 END) AS jan,
    (CASE WHEN (EXTRACT(MONTH FROM logdate))=2 THEN 1 ELSE 0 END) AS feb,
    ...
    FROM mytable
    WHERE EXTRACT(YEAR FROM logdate) = '2009'
) as sub