将值与SQl中的表进行比较

时间:2013-01-04 13:32:35

标签: sql sql-server tsql

这是MyTable结构

MyTable : ID, Date 

Select ID, Date from MyTable

ID     Date

50    2013-01-01 00:00:00.000 
51    2013-01-02 00:00:00.000 
52    2013-01-02 00:00:00.000 

我需要得到这样的结果。

ID     Date

50    2013-01-01 00:00:00.000
50    2013-01-02 00:00:00.000
50    2013-01-03 00:00:00.000 

51    2013-01-02 00:00:00.000 
51    2013-01-03 00:00:00.000

52    2013-01-03 00:00:00.000 

我如何得到结果?

2 个答案:

答案 0 :(得分:4)

好像你想得到一份日期清单。因此,您可以使用递归CTE获取日期列表:

;with data(id, date) as
(
  select id, date
  from mytable
  union all
  select id, dateadd(day, 1, date)
  from data
  where dateadd(day, 1, date) <= '1/3/2013'
)
select *
from data
order by id

SQL Fiddle with Demo。这将生成表格中当前日期与您提供的结束日期之间每个ID的日期列表。在我的示例中,它是1/3/2013

答案 1 :(得分:0)

我认为如果ID列上有CLUSTERED INDEX,这只会更快一些,否则bluefeet的解决方案太棒了!

SELECT T1.ID
        ,Date = DATEADD(DAY, -ROW_NUMBER() OVER (PARTITION BY T1.ID ORDER BY (SELECT NULL))+1, '2013-01-03')
FROM MyTable T1
JOIN MyTable T2 ON T1.ID <= T2.ID