I have two tables with the following structure:
DECLARE @Table1 TABLE
(
IdColumn INT,
DateColumn DATETIME
)
DECLARE @Table2 TABLE
(
IdColumn INT,
DateColumn DATETIME,
Value NUMERIC(18,2)
)
What i want to do is get the latest value from table2 having a less or equal date in table1.
This is the query i build:
SET NOCOUNT ON
DECLARE @Table1 TABLE
(
IdColumn INT,
DateColumn DATETIME
)
DECLARE @Table2 TABLE
(
IdColumn INT,
DateColumn DATETIME,
Value NUMERIC(18,2)
)
DECLARE @RefDate DATETIME='2012-09-01'
DECLARE @NMonths INT
DECLARE @MonthsCounter INT=1
SELECT @NMonths=DATEDIFF(MM,'2012-09-01','2013-03-01')
WHILE @MonthsCounter<=@NMonths
BEGIN
INSERT INTO @Table1
SELECT 1,@RefDate
SET @RefDate=DATEADD(MM,1,@RefDate);
SET @MonthsCounter+=1;
END
INSERT @Table2
SELECT 1,'2012-09-01',1000
UNION
SELECT 1,'2012-12-01',5000
UNION
SELECT 1,'2013-01-01',3000
SELECT
T1.IdColumn,
T1.DateColumn,
T2.Value
FROM @Table1 T1
LEFT JOIN @Table2 T2
ON T2.IdColumn=T1.IdColumn AND T1.DateColumn>=t2.DateColumn
The problem is when a new value comes with a more recent date, i get all values until that date.
IdColumn DateColumn Value
----------- ----------------------- ---------------------------------------
1 2012-09-01 00:00:00.000 1000.00
1 2012-10-01 00:00:00.000 1000.00
1 2012-11-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 1000.00
1 2013-01-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 3000.00
1 2013-02-01 00:00:00.000 1000.00
1 2013-02-01 00:00:00.000 5000.00
1 2013-02-01 00:00:00.000 3000.00
The desired output is this one:
IdColumn DateColumn Value
----------- ----------------------- ---------------------------------------
1 2012-09-01 00:00:00.000 1000.00
1 2012-10-01 00:00:00.000 1000.00
1 2012-11-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 3000.00
1 2013-02-01 00:00:00.000 3000.00
How can i solve this ?
Thanks.
I am just posting Gordon's Answer with correct syntax :
select t1.*,
(select top 1 value
from @table2 t2
where t2.IdColumn = t1.IdColumn and
t2.DateColumn <= t1.DateColumn
order by t2.DateColumn desc
) t2value
from @table1 t1
I would do this with a correlated subquery:
select t1.*,
(select top 1 value
from @table2 t2
where t2.idColumn = t1.idColumn and
t2.dateColumn <= t1.dateColumn
order by t2.dateColumn desc
) t2value
from @table1 t1;
After comment, try this:
INSERT INTO #Table1 (IdColumn, DateColumn)
SELECT IdColumn, DateColumn
FROM #Table2 t
WHERE NOT EXISTS
(
SELECT 'X'
FROM #Table2 tcopy
where t.IdColumn = tcopy.IdColumn
and convert(date, t.DateColumn) = convert(date, tcopy.DateColumn)
and tCopy.DateColumn > t.DateColumn
)
I used ">" because you told me, there are no rows with the same date/time in your table2
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.