错误:聚合函数调用无法嵌套-POSTGRESQL

时间:2019-10-15 17:58:09

标签: sql postgresql

我正在尝试创建一个具有30天记录历史记录的选择,其中values列得到计数,我只是希望它可以添加每天返回的值。

查询

SELECT
    date_update AS Time,
    SUM(COUNT(values)) as "Value"
FROM
    tb_get_metrics
WHERE
    data_update >= CURRENT_DATE - 30
GROUP BY Time
ORDER BY Time

示例输出:

       Time                      Value
2019-10-14 09:46:54.789772        30
2019-10-15 09:46:54.789772        50
2019-10-16 09:46:54.789772        70

选择*来自tb_get_metrics

  date_update(TimeStamp)        value(String)
2019-10-14 09:46:54.789772        apple
2019-10-14 09:46:55.789772        apple
2019-10-14 09:46:56.789772        apple
2019-10-14 09:46:57.789772        apple
2019-10-14 09:46:58.789772        apple
2019-10-14 09:46:59.789772        apple
2019-10-14 09:47:00.789772        apple
2019-10-14 09:46:01.789772        apple
2019-10-14 09:46:02.789772        apple
2019-10-14 09:46:03.789772        apple
2019-10-14 09:46:04.789772        apple
2019-10-14 09:46:05.789772        apple
2019-10-15 09:46:03.789772        potato
2019-10-15 09:46:04.789772        potato
2019-10-15 09:46:05.789772        potato
...

3 个答案:

答案 0 :(得分:1)

您需要舍入日期的时间:

SELECT
    date_update::date AS "Date",
    COUNT(values) as "Value"
FROM
    tb_get_metrics
WHERE
    data_update >= CURRENT_DATE - 30
GROUP BY Time
ORDER BY Time

答案 1 :(得分:1)

仅从每个时间戳中获取日期部分以进行分组:

SELECT
    date_update::date AS Time,
    COUNT(values) AS "Value"
FROM tb_get_metrics
WHERE date_update >= CURRENT_DATE - 30
GROUP BY Time
ORDER BY Time

答案 2 :(得分:1)

通过截断时间戳记的时间,您可以仅关注日期,这是您的WHERE子句试图做到的:

postgres=# SELECT
    date_update::date AS "Date",
    COUNT(values) as "Count"
FROM
    tb_get_metrics
WHERE
    date_update::date >= CURRENT_DATE - 30
GROUP BY "Date"           
ORDER BY "Date";
    Date    | Count 
------------+-------
 2019-10-14 |    24
 2019-10-15 |     6
(2 rows)