您可以使用派生表ROW_NUMBER
和分区来解决此问题。这样做可以消除使用DATEPART
函数和dw
(星期几)参数的周末来忽略任何周六和周日。对于假期,你必须有假期日期表,因为假期完全是主观的。
ROW_NUMBER
允许您获得给定自定义排序和分区的行号索引。我们按货币进行分割,因此每次我们点击一种新货币时索引都会重置,我们按DATE DESC
订购,因此每种货币的最近日期为1
。
-- create a sample table with the date, currency, and exchange rate
create table rates (
id int identity(1,1) primary key,
date date not null,
currency char(3) not null,
rate decimal(10,2) not null
)
go
-- create table of holidays we'll use for excluding rates records later
create table holidays (
id int identity(1, 1) primary key,
date date not null,
name varchar(100) not null
)
-- create some sample data
-- Feb 18 and 19 are Saturday and Sunday
insert into rates (date, currency, rate) values
('2017-02-16', 'GBP', 1.23),
('2017-02-17', 'GBP', 1.24),
('2017-02-18', 'GBP', 1.25),
('2017-02-19', 'GBP', 1.26),
('2017-02-20', 'GBP', 1.27),
('2017-02-16', 'SGD', 2.23),
('2017-02-17', 'SGD', 2.24),
('2017-02-18', 'SGD', 2.25),
('2017-02-19', 'SGD', 2.26),
('2017-02-20', 'SGD', 2.27);
insert into holidays (date, name) values
('2017-02-20', 'National Cherry Pie Day'); -- this is a real thing
with t as (
select id,
date,
currency,
rate,
row_number() over (partition by currency order by date desc) as age
from rates
where datepart(dw, date) not in (1, 7) -- sunday, saturday
and date not in (select date from holidays) -- exclude holiday rates
)
select * from t where age = 1;
您是否试过在最后包含'WHERE'子句?就像'WHERE a.Date = b.Date'? – David
替换???????用GROUP BY查询。 – jarlh