I have a table of stock prices and need to get prices for the 1st day of each week. This SQL in the WHERE clause works well,
DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
except when the market is closed on Monday. Labor Day is a good example. I thought using COALESCE would give me the price on Tuesday if one were unavailable for Monday, but this didn't work.
coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1)).
Can someone help with this?
declare @t table (PriceDt datetime, Symbol nvarchar(10), OpenPric float, ClosePrice float)
insert @t values ('2010-08-02 00:00:0.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-09 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-16 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-23 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-08-30 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-07 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-13 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-20 00:00:00.000', 'SYM', 15.00, 15.10)
insert @t values ('2010-09-27 00:00:00.000', 'SYM', 15.00, 15.10)
select * from @t
where PriceDt = coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1))
(missing 2010-09-07 00:00:00.000 in the result)
2010-08-02 00:00:00.000 SYM 15 15.1 2010-08-09 00:00:00.000 SYM 15 15.1 2010-08-16 00:00:00.000 SYM 15 15.1 2010-08-23 00:00:00.000 SYM 15 15.1 2010-08-30 00:00:00.000 SYM 15 15.1 2010-09-13 00:00:00.000 SYM 15 15.1 2010-09-20 00:00:00.000 SYM 15 15.1 2010-09-27 00:00:00.000 SYM 15 15.1