SQL 如何显示 Return 和购买日期之间的月份差异
SQL How To Display Month Difference Between Return And Purchase Date
我需要帮助来编写查询,以说明 return 和购买日期之间的月份差异,请参见下面的示例。
产品
购买日期 (dd/mm/yy)
返回日期 (dd/mm/yy)
月(预期结果)
A车
2021 年 1 月 1 日
15/01/2021
第 0 个月
B车
2021 年 1 月 1 日
2021 年 2 月
第 1 个月
C车
2021 年 1 月 1 日
2021 年 1 月 3 日
第 2 个月
其中 Month0 = 同月,Month1 = 下个月,依此类推。
我考虑过使用 MONTH 函数。像 MONTH(ReturnDate) - MONTH(PurchaseDate) 这样的东西,但是,当我有不同的年份时,我发现了一个问题。非常感谢您的帮助。
提前致谢!
您可以在 MS SQL 中使用 datediff
功能。我假设这在您的 SQL.
版本中可用
在下面的示例中,我使用的是日期格式 mm/dd/yyyy
,但您可以更改
根据您的示例将其设置为 dd/mm/yyyy
。
select 'Month' + cast(datediff(month, '01/01/2021', '01/15/2021') as varchar)
select 'Month' + cast( datediff(month, '01/01/2021', '02/20/2022') as varchar)
-- output statement 1
Month0
-- output statement 2
Month13
如果您使用的是 SQL 服务器,那么您可以使用 datediff()
来获取差异,然后使用字符串 'Month'.
concat()
select Product, PurchaseDate, ReturnDate,
concat('Month',datediff(month,PurchaseDate,ReturnDate))Month
from yourtable
正如您在问题中提到的,您还可以使用 Month()
函数获取两个月份,然后从购买月份中减去 Return 月份
select Product, PurchaseDate, ReturnDate,
concat('Month',month(ReturnDate)-month(PurchaseDate))Month
from yourtable
对于 MySQL 它将是 timestampdiff()
select Product, PurchaseDate, ReturnDate,
concat('Month',timestampdiff(month,PurchaseDate,ReturnDate))Month
from yourtable
对于 Oracle,它将是 MONTHS_BETWEEN()
。在这种情况下,较大的日期将首先放入函数中,然后是较小的日期。
select Product, PurchaseDate, ReturnDate,
concat('Month',MONTHS_BETWEEN(ReturnDate,PurchaseDate))Month
from yourtable
我需要帮助来编写查询,以说明 return 和购买日期之间的月份差异,请参见下面的示例。
产品 | 购买日期 (dd/mm/yy) | 返回日期 (dd/mm/yy) | 月(预期结果) |
---|---|---|---|
A车 | 2021 年 1 月 1 日 | 15/01/2021 | 第 0 个月 |
B车 | 2021 年 1 月 1 日 | 2021 年 2 月 | 第 1 个月 |
C车 | 2021 年 1 月 1 日 | 2021 年 1 月 3 日 | 第 2 个月 |
其中 Month0 = 同月,Month1 = 下个月,依此类推。
我考虑过使用 MONTH 函数。像 MONTH(ReturnDate) - MONTH(PurchaseDate) 这样的东西,但是,当我有不同的年份时,我发现了一个问题。非常感谢您的帮助。
提前致谢!
您可以在 MS SQL 中使用 datediff
功能。我假设这在您的 SQL.
在下面的示例中,我使用的是日期格式 mm/dd/yyyy
,但您可以更改
根据您的示例将其设置为 dd/mm/yyyy
。
select 'Month' + cast(datediff(month, '01/01/2021', '01/15/2021') as varchar)
select 'Month' + cast( datediff(month, '01/01/2021', '02/20/2022') as varchar)
-- output statement 1
Month0
-- output statement 2
Month13
如果您使用的是 SQL 服务器,那么您可以使用 datediff()
来获取差异,然后使用字符串 'Month'.
select Product, PurchaseDate, ReturnDate,
concat('Month',datediff(month,PurchaseDate,ReturnDate))Month
from yourtable
正如您在问题中提到的,您还可以使用 Month()
函数获取两个月份,然后从购买月份中减去 Return 月份
select Product, PurchaseDate, ReturnDate,
concat('Month',month(ReturnDate)-month(PurchaseDate))Month
from yourtable
对于 MySQL 它将是 timestampdiff()
select Product, PurchaseDate, ReturnDate,
concat('Month',timestampdiff(month,PurchaseDate,ReturnDate))Month
from yourtable
对于 Oracle,它将是 MONTHS_BETWEEN()
。在这种情况下,较大的日期将首先放入函数中,然后是较小的日期。
select Product, PurchaseDate, ReturnDate,
concat('Month',MONTHS_BETWEEN(ReturnDate,PurchaseDate))Month
from yourtable