返回从现在到日期时间值SQL之间的月份数



对不起,我是SQL的新手。我正在使用BigQuery。我有一个名为";last_engaged_ date";,此字段是日期时间值(2021-12-12 00:00:00 UTC(。我正试图对记录的数量进行计数;"订婚";12个月前、18个月前和24个月前基于该领域。起初,为了简单起见,我只是想统计一下每年的记录数量,比如:

Select count(id), year(last_engaged_date) as last_engaged_year
from xyz
group by last_engaged_year
order by last_engaged_year asc

我知道这个查询有很多问题,但主要是BQ说";年份";不是有效的函数吗?不管怎样,我真正需要的是:

Date() - last_engaged_date = int(# of months)
count if <= 12 months as "12_months_count" (# of records where now - last engaged date is less than or equal to 12 months)
count if <= 18 months as "18_months_count"
count if <= 24 months as "24_months_count"

这样我就可以统计出每个last_engaged_date周期有多少条记录。

我希望这是有道理的。非常感谢你的任何想法

〔如何〕返回从现在到日期时间值之间的月数〔在BigQuery中〕SQL

最简单的方法就是使用DATE_DIFF函数,如下例所示

date_diff(current_date(), date(last_engaged_date), month)    

最新更新