我有一个包含2列的表格:Horse和RaceDate。我想创建第三列,为每匹马显示每个RaceDate的30天内的Racedate数量,比每个Racedate的30天内少。我正在尝试通过相关的子查询来做到这一点,但是因为我正在将一个字段与选择的2个字段进行比较,所以显然不起作用。我真的不想恢复为将其视为游标,对此有解决方案吗?
select I.Last30Days,O.Horse,O.RaceDate from Rep2.AuditTrail O
where dateadd(d,-30,O.Racedate) > select I.RaceDate, count(I.RaceDate) as
Last30Days
from Rep2.AuditTrail I
where I.Horse = O.Horse
group by I.RaceDate
答案 0 :(得分:3)
如果我的理解正确,您可以使用CROSS APPLY
进行修改。
create table AuditTrail (
Horse varchar(50),
Racedate date
);
INSERT INTO AuditTrail VALUES ('AA','2018-01-01');
INSERT INTO AuditTrail VALUES ('AA','2018-02-01');
INSERT INTO AuditTrail VALUES ('AA','2018-03-08');
INSERT INTO AuditTrail VALUES ('AA','2018-04-01');
查询1 :
select O.Horse,O.Racedate,COUNT(Last30Days) Last30Days
from Rep2.AuditTrail O
CROSS APPLY (
select I.RaceDate as Last30Days
from Rep2.AuditTrail I
where I.Horse = O.Horse AND DATEDIFF(DAY,i.RaceDate,O.RaceDate)>30
) t1
group by O.Horse,O.Racedate
Results :
| Horse | Racedate | Last30Days |
|-------|------------|------------|
| AA | 2018-02-01 | 1 |
| AA | 2018-03-08 | 2 |
| AA | 2018-04-01 | 2 |
答案 1 :(得分:2)
使用“选择”中的子查询尝试该查询
select
O.Horse,
O.RaceDate,
( Select Count(*)
From AuditTrail
Where Horse=O.Horse
and DATEDIFF(DAY,RaceDate,O.RaceDate)<=30 ) as Last30Days
from Rep2.AuditTrail O