选择具有重叠条件的不同记录

时间:2018-02-09 07:10:13

标签: vertica

我有一个查询可以选择'2017-01-01'和'2017-03-01'之间的日期计数 无论如何都要单独计算“2017-01-01”,“2017-02-01”和“2017-03-01”而不使用案例陈述。

像使用分组

2 个答案:

答案 0 :(得分:1)

您需要功能date_trunc。它会将您的日期/时间戳截断为月份。

daniel=> select date_trunc('month', '2017-01-31'::date);
     date_trunc  
---------------------
 2017-01-01 00:00:00
(1 row)

daniel=> select date_trunc('month', '2017-03-17'::date);
     date_trunc  
---------------------
 2017-03-01 00:00:00
(1 row)

即。查询将类似于:

SELECT
    date_trunc('month', date) as 'month',
    count(*)                  as 'count'
FROM
    table
WHERE
    date_trunc('month', date) >= '2017-01-01'
        AND
    date_trunc('month', date) <= '2017-03-01'
GROUP BY
    date_trunc('month', date);

如果您需要生成时间序列,请使用row_number() over ()和任何有足够行的表格,例如system_tables

daniel=> select '2017-01-01'::DATE + cast(row_number() over () - 1 as interval month) from system_tables limit 5;
      ?column?
---------------------
 2017-01-01 00:00:00
 2017-02-01 00:00:00
 2017-03-01 00:00:00
 2017-04-01 00:00:00
 2017-05-01 00:00:00
(5 rows)

您也可以尝试TIMESERIES填空:

SELECT ts AS 'date' FROM (
    SELECT '2017-01-01'::TIMESTAMP AS tm
        UNION
    SELECT '2017-01-03'::TIMESTAMP AS tm) AS t
TIMESERIES ts AS '8 hours' OVER (ORDER BY tm);

daniel=> \e
        date
---------------------
 2017-01-01 00:00:00
 2017-01-01 08:00:00
 2017-01-01 16:00:00
 2017-01-02 00:00:00
 2017-01-02 08:00:00
 2017-01-02 16:00:00
 2017-01-03 00:00:00
(7 rows)

现在,让我们将所有内容合并在一起,并使用date_trunc计算每月的天数:

SELECT
    date_trunc('month', T.date) AS 'MONTH',
    count(*)                    AS 'COUNT'
FROM (
    SELECT ts::DATE AS 'date' FROM (
        SELECT '2017-01-01'::TIMESTAMP AS tm
            UNION ALL
        SELECT '2017-03-01'::TIMESTAMP AS tm
    ) AS S
    TIMESERIES ts AS '8 hours' OVER (ORDER BY tm)
) AS T
GROUP BY 1
ORDER BY 1;

daniel=> \e
        MONTH        | COUNT
---------------------+-------
 2017-01-01 00:00:00 |    93
 2017-02-01 00:00:00 |    84
 2017-03-01 00:00:00 |     1
(3 rows)

答案 1 :(得分:0)

#!/bin/sh
#SBATCH -N 1      
#SBATCH -n 1      
#SBATCH -c 4      
#SBATCH --mem=10  
#SBATCH -t 0:01:00

module load python
python main.py

或者您可以更改日期包含或独占