簡體   English   中英

獲取 SQL Bigquery 中所有記錄的每日記錄數,select 語句中的子查詢

[英]Get count of records per day for all records in SQL Bigquery, subquery in select statement

我正在嘗試編寫一個查詢,該查詢使用子查詢來生成包含記錄數的列。 我在下面和代碼后面的表中編寫了代碼,當我刪除子查詢時,我確實生成列消息和 count_date 但無法生成列 terr 和 sat(這些列將在子查詢中)。 我已經能夠為一條歷史記錄做到這一點,但當我使用超過 1 的間隔時就不行了。

我需要在我的子查詢中進行什么更改才能獲得 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;  

我的想法如下,對我來說,我將回去 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. 


通過查看您的查詢和預期結果,我懷疑您實際上是在尋找條件聚合。 如果是這樣,則不需要子查詢,您可以簡單地進行條件求和,如下所示:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM