我希望查询一些数据,要求是这样的:
我查询的条件是根据日期(DTime)及类型(Type)来查询的,表名为XX
类型Type包括A和B
我希望查询到的结果是:
当DTime=查询时间时,我对于Type没有要求,即查出这天Type为A和B的所有数据,对于DTime<查询时间时,我希望查出所有Type为B的的数据,A的数据不显示。我希望用一条Sql语句来实现换个说法:我希望查询小于等于<='2006-01-31'的数据,对于时间='2006-01-31'的数据,我要查询的Type没有限制,但是对于时间<'2006-01-31'的数据,我只要查询出Type为B的数据。请高手指点

解决方案 »

  1.   

    SELECT * FROM TB WHERE DTIME<'2006-01-31' AND TYPE='B'
    UNION
    SELECT * FROM TB WHERE DTIME='2006-01-31'
      

  2.   

    ----创建测试数据
    declare @xx table(dtime datetime,type varchar(10))
    insert @xx
    select '2006-01-31','A' union all
    select '2006-01-31','B' union all
    select '2006-01-30','A' union all
    select '2006-01-30','B' union all
    select '2006-01-30','A' union all
    select '2006-01-30','B'
    ----查询
    declare @dt datetime
    set @dt = '2006-01-31'
    select * from @xx where dtime < @dt
    union all
    select * from @xx where datediff(dd,dtime,@dt) = 0 and type = 'B'
      

  3.   

    declare @xx table(dtime datetime,type varchar(10))
    insert @xx
    select '2006-01-31','A' union all
    select '2006-01-31','B' union all
    select '2006-01-30','A' union all
    select '2006-01-30','B' union all
    select '2006-01-30','A' union all
    select '2006-01-30','B' union all
    select '2006-01-29','A' union all
    select '2006-01-29','B' union all
    select '2006-01-29','A' union all
    select '2006-01-29','B'
    ----查询
    declare @dt datetime
    set @dt = '2006-01-31'
    select * from @xx where dtime < @dt  and type = 'B'
    union all
    select * from @xx where datediff(dd,dtime,@dt) = 0