简体   繁体   中英

Compare values with in a table in SQl

This is MyTable structure

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 

I need to get the result like this.

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 

How do i get the results ?

Seems like you want to get a list of dates. Of so, then you can use a recursive CTE to get the list of dates:

;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

See SQL Fiddle with Demo . This will generate the list of dates for each ID between the current date in your table and the end date that you provide. In my example it is 1/3/2013

I think this will work a bit faster ONLY if there is a CLUSTERED INDEX on the ID column, else bluefeet's solution is fantastic!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM