从表中选择日期为两列

时间:2017-08-16 15:23:39

标签: sql sql-server

我有一张桌子,其中一个字段是日期字段。

我被要求编写一个查询,在A列中返回不同日期(有序)的列表,然后有另一列,比如说日期B,其中B列中的日期是小于列的最大日期甲

    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      

5 个答案:

答案 0 :(得分:7)

如果你正在使用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

答案 1 :(得分:2)

你可以用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

答案 2 :(得分:1)

您可以使用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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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