这可以转换为基于集合的查询吗?

时间:2014-06-30 17:23:03

标签: sql sql-server tsql sql-server-2012

我有这个问题:

if OBJECT_ID('tempdb..#tempA') is not null drop table #tempA

create table #tempA
(
    tempid varchar(5),
    tempdate smalldatetime
)

declare @loopdate smalldatetime
set @loopdate = '4/2/2013'

while (@loopdate <= '4/28/2013')
begin
    --Purpose is to get IDs not in TableB for each date period
    insert into #tempA (tempid, tempdate)
    select storeid, @loopdate
    from
    (
        select tableAid
        from tableA
        except
        select tableBid
        from tableB
        where tableBdate = @loopdate
    ) as idget

    set @loopdate = DATEADD(day, 1, @loopdate)
end

有没有办法让while循环设置为基础,还是可以做到最好?

编辑:对正确性进行了更改

编辑:最终结果

ID1 4/2/2014
ID2 4/2/2014
ID4 4/2/2014
ID2 4/3/2014
ID1 4/4/2014
ID5 4/4/2014
ID3 4/5/2014

4 个答案:

答案 0 :(得分:1)

仍然是循环但可能更高效

while (@loopdate <= '4/28/2013')
begin
    --Purpose is to get IDs not in TableB for each date period
    insert into #tempA (tempid, tempdate)
    select storeid, @loopdate
    from
    (
        select tableAid
          from tableA
          left join tableB 
            on tableB.tableBid = tableA.tableAid
           and tableB.tableBdate = @loopdate 
         where tableB.tableBid is null
    ) as idget

    set @loopdate = DATEADD(day, 1, @loopdate)
end

这需要一些工作,但可以通过一套

让你一路走来
;WITH Days
as
(
    SELECT cast('4/2/2013' AS datetime ) as 'Day'
    UNION ALL
    SELECT DATEADD(DAY, +1, Day) as 'Day'
      FROM Days
     where [DAY] <= '4/28/2013'
)
SELECT tableA.tableAid, Days.[Day] 
  from Days 
  left join tableB 
    on tableB.tableBdate = Days.[Day]
  full join tableA 
    on tableB.tableBid = tableA.tableAid 
 where tableB.tableBid is null

答案 1 :(得分:1)

这取决于tableA是否有日期,如果没有,则取决于:

WITH DateList(DateDay) AS 
(  
     SELECT CAST('2013-04-28' AS DATETIME)
        UNION ALL
    SELECT DATEADD(DAY, DATEDIFF(DAY,0,DATEADD(DAY, -1, DateDay)),0)  
    FROM DateList  
    WHERE DateDay between '2013-04-03' and '2013-04-28'
)  
SELECT DISTINCT
    tableAid
    , DateDay 
FROM DateList
  cross join #tableA a
  left join #tableB b
    on tableAid = b.tableBid
    and b.tableBdate = DateDay
where
    b.tableBid is null
ORDER BY
    DateDay ASC

答案 2 :(得分:0)

insert into #tempA (tempid, tempdate)
select tableAid, tableAdate
from tableA
except
select tableBid,tableBdate
from tableB
where tableBdate >= '4/2/2013' and tableBdate <= '4/28/2013';

答案 3 :(得分:-1)

您可以在条件子句中包含日期范围,如下所示:

insert into #tempA (tempid, tempdate)
select tableAid
from tableA
except
select tableBid
from tableB
where tableBdate >= '4/2/2013' and tableBdate <= '4/28/2013';