需要帮助您了解如何计算两个日期之间的月份,能够计算日期之间的月份,而不是年份
ID StartDate Enddate
1 1/1/2016 4/23/2019
2 1/1/2016 4/30/2017
3 1/1/2016 12/31/2018
4 1/1/2017 4/23/2019
5 5/20/2017 11/30/2017
ID StartDate Enddate 2016 2017 2018 2019
1 1/1/2016 4/23/2019 12 12 12 4
2 1/1/2016 4/30/2017 12 4 0 0
3 1/1/2016 12/31/2018 12 12 12 0
4 1/1/2017 4/23/2019 0 12 12 4
5 5/20/2017 11/30/2017 0 7 0 0
答案 0 :(得分:0)
在SQL Server中,这样的间隔计数很难。如果数据库支持least()
和greatest()
,则要简单得多。这是一种冗长的方法:
select id, startdate, enddate,
(case when startdate >= '2017-01-01' or enddate < '2016-01-01' then 0
when startdate < '2016-01-01' and enddate >= '2017-01-01' then 12
when startdate >= '2016-01-01' and enddate >= '2017-01-01' then 13 - month(startdate)
when startdate < '2016-01-01' then month(enddate)
else month(enddate) + 1 - month(startdate)
end) as months_2016,
(case when startdate >= '2018-01-01' or enddate < '2017-01-01' then 0
when startdate < '2017-01-01' and enddate >= '2018-01-01' then 12
when startdate >= '2017-01-01' and enddate >= '2018-01-01' then 13 - month(startdate)
when startdate < '2017-01-01' then month(enddate)
else month(enddate) + 1 - month(startdate)
end) as months_2017,
(case when startdate >= '2019-01-01' or enddate < '2018-01-01' then 0
when startdate < '2018-01-01' and enddate >= '2019-01-01' then 12
when startdate >= '2018-01-01' and enddate >= '2019-01-01' then 13 - month(startdate)
when startdate < '2018-01-01' then month(enddate)
else month(enddate) + 1 - month(startdate)
end) as months_2018
from t;
这基本上处理了不同的条件,即开始日期是在相关年份之前,期间还是之后,而结束日期是相同的。
答案 1 :(得分:0)
如果表中有年份,则可以像这样进行动态透视,这样可以省去手动声明列的麻烦:
extension Data {
func toByteArray() -> [UInt8]? {
var byteData = [UInt8](repeating:0, count: self.count)
self.copyBytes(to: &byteData, count: self.count)
return byteData
}
}