我已经过了很多天,我想用大查询SQL找出那个特定日间隙的月份和年份
例如:我有以下字段:date_today为DATE,day_passed 作为INTEGER
date_today = '2018-01-22'
day_passed = 32
从这一天起,我想使用day_passed列值
创建一个如下所示的新列 month_joined = '2017-12'
挑战:月份可能有不同的日子2月(28或29),30,31
解决此问题的最佳方法是什么?
答案 0 :(得分:2)
在tsql中,您可以使用此查询,我建议您将其修改为函数。
declare @date nvarchar(20) = '2018-01-22'
declare @interval int = -32
declare @newDate datetime = DATEADD(DAY,@interval,CAST(@date as datetime))
select cast(year(@newDate) as nvarchar(4)) +'-'+ cast(month(@newDate) as nvarchar(2)) as 'month_joined'
在tsql中创建函数:
CREATE FUNCTION YearMonthConvert(
@Date datetime,
@Interval int = 0)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE @newDate datetime = DATEADD(DAY,@Interval,CAST(@Date as datetime))
RETURN cast(year(@newDate) as nvarchar(4)) +'-'+ cast(month(@newDate) as nvarchar(2))
END;
然后就可以这样调用:
select dbo.yearmonthconvert('2018-01-22',-32)
我相信mysql语法如下 - 没有完成mysql所以如果有人想在评论中纠正我,那将非常感激。
set @date = '2018-01-22';
set @interval = -32;
set month_joined = DATE_ADD(@date, INTERVAL @interval DAY);
答案 1 :(得分:0)
答案 2 :(得分:0)
以下是BigQuery Standard SQL
它应该让您了解如何使用BigQuery中的日期
#standardSQL
SELECT
date_today,
day_passed,
DATE_SUB(date_today, INTERVAL day_passed DAY) day_joined,
DATE_TRUNC(DATE_SUB(date_today, INTERVAL day_passed DAY), MONTH) month_joined_as_date,
FORMAT_DATE('%Y-%m', DATE_SUB(date_today, INTERVAL day_passed DAY)) month_joined_as_string
FROM `yourproject.yourdataset.yourtable`
您可以使用您问题中的虚拟数据进行上述测试/播放,如下所示
#standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
SELECT DATE '2018-01-22' date_today, 32 day_passed
)
SELECT
date_today,
day_passed,
DATE_SUB(date_today, INTERVAL day_passed DAY) day_joined,
DATE_TRUNC(DATE_SUB(date_today, INTERVAL day_passed DAY), MONTH) month_joined_as_date,
FORMAT_DATE('%Y-%m', DATE_SUB(date_today, INTERVAL day_passed DAY)) month_joined_as_string
FROM `yourproject.yourdataset.yourtable`
结果
date_today day_passed day_joined month_joined_as_date month_joined_as_string
2018-01-22 32 2017-12-21 2017-12-01 2017-12
答案 3 :(得分:-1)
我在bigquery中以一种简单的方式解决了它
SUBSTR(STRING(DATE_ADD(DATE(date_today), -day_passed, "DAY")),1,7) AS month_joined