假设数据在vt表中, date, postdate都为datetime类型(SQL Server 2005或以上适用), 查询结果未对日期值进行格式化, 查询SQL如下:
select d.monthTxt,
max(case when d.idx = 1 then d.date else null end) as date1,
max(case when d.idx = 2 then d.date else null end) as date2,
max(case when d.idx = 1 then d.postdate else null end) as postdate1,
max(case when d.idx = 2 then d.postdate else null end) as postdate2
from (
select s.date, s.postdate,
left(convert(nvarchar(10), s.date, 120), 7) as monthTxt,
row_number() over (partition by left(convert(nvarchar(10), s.date, 120), 7) order by s.date) as idx
from vt s
) d
where d.idx in (1, 2)
group by d.monthTxt
结果如下图:
SQL说明:
left(convert(nvarchar(10), s.date, 120), 7)是获取月份的字串, 就是上图的monthTxt;
里面的子查询使用了row_number分组编号, 按月份字串进行分组, date值升序进行排序编号:
row_number() over (partition by left(convert(nvarchar(10), s.date, 120), 7) order by s.date) as idx;
最外面的查询则按月份分组查询, 获取每月前两个日期date, postdate值