[英]selecting dates from a table into two columns
我有一张桌子,其中一个字段是日期字段。
我被要求编写一个查询,在A列中返回不同日期(有序)的列表,然后有另一列,比如说日期B,其中B列中的日期是小于A列的最大日期。
MyDateField
2017-01-01
2017-01-01
2017-01-01
2017-01-02
2017-01-02
2017-01-03
2017-01-04
2017-01-05
2017-01-05
2017-01-05
需要回答
2017-01-05 2017-01-04
2017-01-04 2017-01-03
2017-01-03 2017-01-02
2017-01-02 2017-01-01
2017-01-01
如果您使用的是SQL-Server 2012+,则可以使用LAG()
从表中获取最后一个最大的日期:
SELECT t.date,
LAG(t.date,1) OVER(ORDER BY t.date) as last_biggest_date
FROM (SELECT DISTINCT s.dateField FROM YourTable s) t
你可以用CTE做其他事情。 这将获取不同日期的列表,然后使用自联接。
with cte as(
select distinct
MyDateField
from
YourTable)
select
c.MyDateField
,max(c2.MyDateField) as MaxDate
from
cte c
left join cte c2 on c2.MyDateField < c.MyDateField
group by
c.MyDateField
order by
c.MyDateField
或者没有CTE的简单自联接
--in this case DISTINCT isn't really needed, but left in case there are other columns
select distinct
c.MyDateField
,max(c2.MyDateField) as MaxDate
from
myTable c
left join myTable c2 on c2.MyDateField < c.MyDateField
group by
c.MyDateField
order by
c.MyDateField
您可以使用apply子查询在第二列中返回较小的日期:
select distinct t1.MyDateField, x.MyDateField
from MyTable t1
outer apply (select max(MyDateField) MyDateField
from MyTable t2
where t1.MyDateField> t2.MyDateField) x
SELECT d, LAG(d) OVER (ORDER BY d) AS d2
FROM (
SELECT DISTINCT d
FROM (VALUES ('2017-01-01'),
('2017-01-01'),
('2017-01-01'),
('2017-01-02'),
('2017-01-02'),
('2017-01-03'),
('2017-01-04'),
('2017-01-05'),
('2017-01-05'),
('2017-01-05')) AS dates(d)
) AS d(d)
ORDER BY d DESC;
输出:
d d2
---------- ----------
2017-01-05 2017-01-04
2017-01-04 2017-01-03
2017-01-03 2017-01-02
2017-01-02 2017-01-01
2017-01-01 NULL
with CTE as(
select
ROW_NUMBER() over (order by MyDateField) 'RN',
MyDateField from TempTable
group by MyDateField)
select t2.MyDateField,t1.MyDateField from CTE t1
right join CTE t2
on t1.RN=t2.RN-1
order by t2.MyDateField desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.