[英]Get count of records per day for all records in SQL Bigquery, subquery in select statement
I'm trying to write a query that uses a subquery to generate a column with the count of records.我正在尝试编写一个查询,该查询使用子查询来生成包含记录数的列。 I've written the code below and in the table after the code, when I remove the subquery I do generate columns messages and count_date but am not able to generate columns terr and sat (these columns would be within the subquery).
我在下面和代码后面的表中编写了代码,当我删除子查询时,我确实生成列消息和 count_date 但无法生成列 terr 和 sat(这些列将在子查询中)。 I've been able to do it for one record of history but not when I use an interval more than 1.
我已经能够为一条历史记录做到这一点,但当我使用超过 1 的间隔时就不行了。
what do I need to change in my subquery to get sat and terr我需要在我的子查询中进行什么更改才能获得 sat 和 terr
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;
My idea is below, for me I'll be going back over 3 months.我的想法如下,对我来说,我将回去 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.
By looking at your query and expected results, I suspect that you are actually looking for conditional aggregation.通过查看您的查询和预期结果,我怀疑您实际上是在寻找条件聚合。 If so, there is no need for a subquery, you can simply do conditional sums, as follows:
如果是这样,则不需要子查询,您可以简单地进行条件求和,如下所示:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.