Den*_*nis 0 sql t-sql sql-server
I have a data table, let's call it dt and a date index table, let's call it dt_idx. I would like to get:
Here is a sql fiddle: Click Here
Here is a sample schema:
CREATE TABLE dt_idx
(
d DATE,
v INT
)
GO
INSERT INTO dt_idx (d, v)
SELECT '2019-02-10', CAST(RAND(CHECKSUM(NEWID())) * 1000 as INT) + 1
UNION
SELECT '2019-03-05', CAST(RAND(CHECKSUM(NEWID())) * 1000 as INT) + 1
CREATE TABLE dt
(
d DATE,
a int,
b int
)
declare @sdate date = '2019-01-01'
, @edate date = '2019-03-24'
; with dates_CTE (date) as (
select @sdate
Union ALL
select DATEADD(day, 1, date)
from dates_CTE
where date < @edate
) select *
into #temp
from dates_CTE
INSERT INTO dt(d, a, b)
SELECT date, CAST(RAND(CHECKSUM(NEWID())) * 1000 as INT) + 1, CAST(RAND(CHECKSUM(NEWID())) * 1000 as INT) + 1
from #temp
Run Code Online (Sandbox Code Playgroud)
Here is the output I am expecting (columns a & b would be some random numbers as per the table):
d | a | b
2019-02-10 123 123
2019-02-11 234 344
2019-02-12 234 344
2019-02-13 234 344
2019-02-14 234 344
2019-03-05 234 344
2019-03-06 234 344
2019-03-07 234 344
2019-03-08 234 344
2019-03-09 234 344
Run Code Online (Sandbox Code Playgroud)
您的问题有点难以理解。我认为您希望其中的所有记录dt都比中的记录晚零到五天dt_idx。
如果是这样,您可以使用exists:
SELECT *
FROM dt
WHERE EXISTS (SELECT 1
FROM dt_idx di
WHERE dt.d >= di.d AND
dt.d < DATEADD(day, 5, di.d)
);
Run Code Online (Sandbox Code Playgroud)