这是我到目前为止的查询:
declare @snaps table (hotel_id int, snapdate date, month int, year
int)
insert into @snaps
select hotel_id, max(import_date) as maximport_date,
month(max(import_date)), year(max(import_Date))
from ukrmc.dbo.block_Res
where import_date between '2017-12-01' and '2018-12-31'
group by month(import_date), year(import_Date), hotel_id--, market_seg
--order by hotel_id, maximport_Date
select otb1.hotel_id
,otb1.snapdate
,otb1.month
,otb1.year
from
(select * from @snaps) otb1
以下是此查询为我提供的一个hotel_id的示例:
hotel_id snapdate month year
3 2017-12-31 12 2017
3 2018-01-31 1 2018
3 2018-02-28 2 2018
3 2018-03-30 3 2018
3 2018-04-30 4 2018
3 2018-05-31 5 2018
3 2018-06-30 6 2018
3 2018-07-31 7 2018
3 2018-08-31 8 2018
3 2018-09-30 9 2018
3 2018-10-06 10 2018
...依次类推,分别是50个hotel_id的
。我现在想要一个列,该列显示快照日期的月份和年份以及接下来的四个月中的每个月份。例如,对于hotel_id 3和快照日期“ 2017-12-31”和“ 2018-01-31”(作为示例),它应如下所示:
hotel_id snapdate month year Month_TY
3 2017-12-31 12 2017 December 2017
3 2017-12-31 12 2017 January 2018
3 2017-12-31 12 2017 February 2018
3 2017-12-31 12 2017 March 2018
3 2017-12-31 12 2017 April 2018
3 2018-01-31 1 2018 January 2018
3 2018-01-31 1 2018 February 2018
3 2018-01-31 1 2018 March 2018
3 2018-01-31 1 2018 April 2018
3 2018-01-31 1 2018 May 2018
我不知道我该怎么做?我需要在select子句中做些什么吗?
答案 0 :(得分:1)
您可以使用CROSS APPLY来计算最终SELECT语句中的5个日期,并使用DATENAME来计算month-year-string:
SELECT hotel_id, snapdate, month, year,
DATENAME(MM, snapdateex) + N' ' + DATENAME(YYYY, snapdateex) AS Month_TY
FROM @snaps
CROSS APPLY (VALUES
(snapdate),
(DATEADD(month, 1, snapdate)),
(DATEADD(month, 2, snapdate)),
(DATEADD(month, 3, snapdate)),
(DATEADD(month, 4, snapdate))) AS hlp(snapdateex)
答案 1 :(得分:0)
我想到的最简单的方法是联合,以及dateadd:
select otb1.hotel_id ,otb1.snapdate ,MONTH(otb1.snapdate) ,YEAR(otb1.snapdate) from (select * from @snaps) otb1
UNION ALL
select otb1.hotel_id ,otb1.snapdate ,MONTH(DATEADD(MONTH, 1 , otb1.snapdate)) ,YEAR(DATEADD(MONTH, 1 , otb1.snapdate)) from (select * from @snaps) otb1
UNION ALL
select otb1.hotel_id ,otb1.snapdate ,MONTH(DATEADD(MONTH, 2 , otb1.snapdate)) ,YEAR(DATEADD(MONTH, 2, otb1.snapdate)) from (select * from @snaps) otb1
UNION ALL
select otb1.hotel_id ,otb1.snapdate ,MONTH(DATEADD(MONTH, 3 , otb1.snapdate)) ,YEAR(DATEADD(MONTH, 3, otb1.snapdate)) from (select * from @snaps) otb1