我想在 Where 条件中输入 2 个日期,一次用于 8 月,一次用于 10 月

Posted

技术标签:

【中文标题】我想在 Where 条件中输入 2 个日期,一次用于 8 月,一次用于 10 月【英文标题】:I would like to enter 2 dates in the Where condition, once for August and once for October 【发布时间】:2020-10-19 14:51:59 【问题描述】:

。不幸的是,我在这里没有进一步说明,因为我只能在 Where 条件中输入日期(从 .. 到),请参阅 AND 日期之间。

SELECT
  subregion1_code,
  subregion1_name,
  SUM(new_confirmed) as august_confirmed,
  SUM(new_tested) as august_tested,
  SUM(new_confirmed) as october_confirmed,
  SUM(new_tested) as october_tested,
  SUM(new_confirmed) / SUM(new_tested) AS positive_test_rate, 
FROM
  `bigquery-public-data.covid19_open_data.covid19_open_data` as B
WHERE
  country_code = "US"
  AND aggregation_level = 1
  AND date BETWEEN '2020-10-01' AND '2020-10-30'
 
GROUP BY
  subregion1_code,
  subregion1_name 
ORDER BY
  positive_test_rate DESC

【问题讨论】:

date 是列名吗? 是否总是比您想要的所选日期提前 2 个月? @Akina 是的 @nbk 不,我想要 8 月的专栏(如 august_confirmed,august_tested)和 10 月的专栏(october_confirmed,october_tested),但应该在一个代码中 【参考方案1】:

您可以使用条件聚合来做到这一点:

SELECT
  subregion1_code,
  subregion1_name,
  SUM(CASE WHEN MONTH(date) = 8 THEN new_confirmed ELSE 0 END) AS august_confirmed,
  SUM(CASE WHEN MONTH(date) = 8 THEN new_tested ELSE 0 END) AS august_tested,
  SUM(CASE WHEN MONTH(date) = 10 THEN new_confirmed ELSE 0 END) AS october_confirmed,
  SUM(CASE WHEN MONTH(date) = 10 THEN new_tested ELSE 0 END) AS october_tested,
  SUM(new_confirmed) / SUM(new_tested) AS positive_test_rate, 
FROM `bigquery-public-data.covid19_open_data.covid19_open_data` AS B
WHERE
  country_code = 'US'
  AND aggregation_level = 1
  AND (date BETWEEN '2020-10-01' AND '2020-10-31' OR date BETWEEN '2020-08-01' AND '2020-08-31')
GROUP BY subregion1_code, subregion1_name 
ORDER BY positive_test_rate DESC

【讨论】:

但这适用于 8 月和 10 月,但我想要 10 月和 9 月的“Where 条件” 我想在 Where 条件中输入 2 个日期,一个是 8 月,一个是 10 月。 九月还是十月?另外:SUM(CASE WHEN MONTH(date) = 8 THEN new_confirmed ELSE 0 END) 仅返回 8 月的总和,SUM(CASE WHEN MONTH(date) = 10 THEN new_confirmed ELSE 0 END) 仅返回 10 月的总和。

以上是关于我想在 Where 条件中输入 2 个日期,一次用于 8 月,一次用于 10 月的主要内容,如果未能解决你的问题,请参考以下文章

熊猫:LEFT OUTER JOIN where(ON)2个匹配的条件[重复]

我想在 where 条件下访问 null 的记录

我想在未来的日期/时间运行一个函数 - 一次 | nodejs - 后端任务?

在where子句期间将十进制转换为日期[重复]

Linq中,怎么写日期类型字段的Where条件语句

C#操作sql时注意点