我正在尝试编写一个查询,该查询使用子查询来生成具有记录数的列。我已经在代码下方和下面的表中编写了代码,当我删除子查询时,我确实生成了列消息和count_date,但无法生成terr和sat列(这些列将在子查询内)。我已经能够完成一项历史记录记录,但是当我使用的间隔大于1时就无法做到。
我需要在子查询中进行些什么更改才能得到
SELECT count(*) as TotalMessages, Date(ingestion_time) as Date_ingestion,
(SELECT count(*)
FROM myTable
WHERE collection_type = '1' AND date(ingestion_time) >=
(DATE_SUB(CURRENT_DATE(), INTERVAL 350 DAY)) AND
date(ingestion_time) < (CURRENT_DATE())
GROUP BY date(ingestion_time)
) AS terr
FROM
myTable
WHERE
date(ingestion_time) >= (DATE_SUB(CURRENT_DATE(), INTERVAL 350 DAY)) AND
date(ingestion_time) < (CURRENT_DATE())
GROUP BY 2
ORDER BY 2;
下面是我的想法,对我来说,我将回去超过3个月。
Messages | count_date | terr | sat
500 | 2019-11-13 | 486 | 14
710 | 2009-11-12 | 700 | 10
450 | 2009-11-11 | 440 | 10
767 | 2009-11-10 | 760 | 7
and so forth until the last possible count from a day.
答案 0 :(得分:2)
通过查看查询和预期结果,我怀疑您实际上是在寻找条件聚合。如果是这样,则不需要子查询,您只需执行条件求和,如下所示:
SELECT
count(*) as TotalMessages,
Date(ingestion_time) as Date_ingestion,
sum(case when collection_type = '1' then 1 end) as terr,
sum(case when not collection_type = '1' then 1 end) as sat
FROM
myTable
WHERE
date(ingestion_time) >= (DATE_SUB(CURRENT_DATE(), INTERVAL 350 DAY)) AND
date(ingestion_time) < (CURRENT_DATE())
GROUP BY 2
ORDER BY 2;