基于月份聚合数据的SQL查询(Postgres)

时间:2018-06-12 12:09:05

标签: postgresql

我查询的表是:

table testing_table:

testType | period_from | period_to| copies |
       1 |     20180101|  20181201|       1|
       2 |    20180101 |  20191201|       1|
       3 |     20190101|  20191201|       1|

我想遍历数组并使用以下查询生成如下值:

DateVar | ABTEST | CDTEST | EFTEST |
20180101|       4|       0|       0|
20180201|       3|       4|       2|

dateVar = ['20180101','20180201','20180501']。

我正在尝试开发像这样的SQL查询:

SELECT
     SUM (
     CASE
     WHEN (testType = 1 AND (period_from <= dateVar AND period_to >= dateVar)) THEN
     copies
     ELSE
     0
     END
     ) AS "ABTEST",
     SUM (
     CASE
     WHEN (testType = 2 AND (period_from <= dateVar AND period_to >= dateVar)) THEN
     copies
     ELSE
     0
     END
     ) AS "CDTEST",
     SUM (
     CASE
     WHEN (testType = 3 AND (period_from <= dateVar AND period_to >= dateVar)) THEN
     copies
     ELSE
     0
     END
     ) AS "EFTEST"
    FROM
     testing_table;

我很遗憾该怎么做。我是否会研究功能?

1 个答案:

答案 0 :(得分:0)

我认为您应该使用不需要的功能来完成您的要求我已经写了一个您可能想要检查的查询

SELECT DTVAR, 
            SUM(CASE 
            WHEN TestType = 1
                THEN copies
            ELSE 0
            END) AS 'ABTEST', 
            SUM(CASE 
            WHEN TestType = 2
                THEN copies
            ELSE 0
            END) AS 'CDTEST', 
            SUM(CASE 
            WHEN TestType = 3
                THEN copies
            ELSE 0
            END) AS 'EFTEST'
FROM (
    SELECT DTVAR, TestType, sum(copies) AS copies
    FROM testing_table
    INNER JOIN (
        SELECT DTVAR
        FROM unnest(dateVar ['20180101','20180201','20180501']) AS DTVAR
        ) AA
        ON (
                period_from <= DTVAR
                AND period_to >= DTVAR
                )
    GROUP BY DTVAR, TestType
    ) A
GROUP BY DTVAR

希望这会有所帮助..