SQL查询卡住 - 在不同的行上进行比较

时间:2012-09-18 20:45:07

标签: sql sql-server sql-server-2008 sql-server-2005

我正在研究SQL的一个非常奇怪的问题,我必须比较之前的行

Number    start_date                      end_date    
 -----     -------                      ------------
 1    2011-06-07 00:00:00.000         2011-07-10 00:00:00.000   
 2    2011-10-11 00:00:00.000         2011-10-11 00:00:00.000   
 3    2011-10-26 00:00:00.000         2011-10-29 00:00:00.000   
 4    2011-10-29 00:00:00.000         2011-11-15 00:00:00.000   

在这里,我必须比较两个不同行上的start_date和end_date,并从中创建一个视图。 (如果start_date小于前一个end_date,则条件设置为1)。

那么它应该比较2011-10-26 00:00:00.000 for 3和2011-10-27 00:00:00.000 on 2 30天

Number    start_date                      end_date                 Criteria
-----     -----------                   ----------------          ------------
1   2011-06-07 00:00:00.000       2011-07-10 00:00:00.000            0
2   2011-10-11 00:00:00.000       2011-10-11 00:00:00.000            0
3   2011-10-26 00:00:00.000       2011-10-29 00:00:00.000            1
4   2011-10-30 00:00:00.000       2011-11-15 00:00:00.000            1   

我很困惑,我应该如何处理这个问题。

任何帮助都会有所帮助!!!!

谢谢!!!

3 个答案:

答案 0 :(得分:2)

最直接的方法是使用子查询:

select A.number, a.start_date, a.end_date,
    CASE WHEN start_date < dateadd(d,30,(select TOP(1) b.end_date
     from mytable B
     where B.number < A.number
     order by B.number desc)) then 1 else 0 end Criteria
from mytable A

注意:如果开始日期是 上一行的结束日期后的第29天,Criteria变为1.到第30天起,它为0.调整{{1根据需要在查询中。

样品:

30

结果:

create table mytable (
    Number int primary key,
    start_date datetime,
    end_date datetime);

insert mytable
select 1, '2011-06-07', '2011-07-10' union all
select 2, '2011-10-11', '2011-10-27' union all
select 3, '2011-10-26', '2011-10-29' union all
select 4, '2011-10-29', '2011-11-15'

答案 1 :(得分:1)

尝试使用case,如下所示:

create view vDates as
select Number,start_date,end_date, 
       case 
         when start_date<end_date 
           then 0
         else 1
       end as Criteria
from tab

SQL Fiddle Demo

答案 2 :(得分:0)

更易读的方法是创建一个函数并发送正确的日期:

功能:

create function [dbo].[CompareDates] (
    @START_DATE datetime,
    @PREVIOUS_END_DATE datetime
)
RETURNS int
AS
BEGIN

    if @START_DATE < @PREVIOUS_END_DATE
        return 1
    return 0

END

查询(使用子查询):

declare @dates table
(
    number int,
    start datetime,
    end_date datetime
)

insert into @dates values
(1, '2011-06-07 00:00:00.000', '2011-07-10 00:00:00.000'),
(2, '2011-10-11 00:00:00.000', '2011-10-27 00:00:00.000'),
(3, '2011-10-26 00:00:00.000', '2011-10-29 00:00:00.000'),
(4, '2011-10-29 00:00:00.000', '2011-11-15 00:00:00.000')

select *, dbo.CompareDates(dates.end_date, dates.previous_end_date)  from
(
    select number, start, end_date,
        (select TOP 1 end_date
        from @dates d2
        where d2.number < d1.number
        order by d2.number desc) as previous_end_date
    from @dates d1
) dates