Sql server TSQL-查找一周中的第一天或第二天

Sql server TSQL-查找一周中的第一天或第二天,sql-server,tsql,stockquotes,Sql Server,Tsql,Stockquotes,我有一张股票价格表,需要得到每周第一天的价格。WHERE子句中的SQL运行良好 DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0) 除非周一市场关闭。劳动节就是一个很好的例子。我原以为如果周一不能买到一台,使用COALESCE会在周二给我定价,但这不起作用 coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1)). 有人能帮忙吗 declare

我有一张股票价格表,需要得到每周第一天的价格。WHERE子句中的SQL运行良好

DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
除非周一市场关闭。劳动节就是一个很好的例子。我原以为如果周一不能买到一台,使用COALESCE会在周二给我定价,但这不起作用

coalesce(DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0), DATEADD(ww, DATEDIFF(ww,0,PriceDt), 1)). 
有人能帮忙吗

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))
(结果中缺少2010-09-07 00:00:00.000)

2010-08-02 00:00:00.000 SYM 15.1 2010-08-09 00:00:00.000 SYM 15.1 2010-08-16 00:00:00.000 SYM 15.1 2010-08-23 00:00:00.000 SYM 15.1 2010-08-30 00:00:00.000 SYM 15.1 2010-09-13 00:00:00.000 SYM 15.1 2010-09-20 00:00:00.000 SYM 15.1 2010-09-27 00:00:00.000 SYM 15.1
这将为您提供表格中每周的最早日期(假设您的一周从周一开始):

现在,您可以将该结果加入到表中,以获得输入数据的每周第一天的价格:

select t.Pricedt, t.Symbol, t.OpenPric, t.ClosePrice
from
(
    select min(Pricedt) Pricedt
    from @t
    group by DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
) d 
join @t t on d.Pricedt = t.PriceDt

如果你一直这样做。如果可以的话,我强烈建议您创建一个日历表。已经有脚本可以执行此操作。该表可以包含诸如iHolday、quarter、Weekday、weekends等内容。这使得这些类型的任务变得更加容易。什么是DBMS服务器?SQL Server/Sybase ASE?什么版本(
SELECT@@version
)?您不能在此处明确使用合并函数,因为从DATEADD(ww,DATEDIFF(ww,0,PriceDt),0)开始的一周的第一天将不为空。你需要另一个专栏来决定什么时候开始一周的第一天,什么时候开始第二天,也许像JChao建议的那样,一个假日表日历表就是最好的选择。
select min(Pricedt) Pricedt
from @t
group by DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
select t.Pricedt, t.Symbol, t.OpenPric, t.ClosePrice
from
(
    select min(Pricedt) Pricedt
    from @t
    group by DATEADD(ww, DATEDIFF(ww,0,PriceDt), 0)
) d 
join @t t on d.Pricedt = t.PriceDt