2

我已经编写了以下查询,但是我收到了一个多部分标识符未绑定错误,因为我正在尝试使用来自子选择外部的第一个内部连接的值来过滤子查询。

SELECT runners.id,  wins
FROM dbHorseRacing.dbo.historic_runners as runners
inner join dbHorseRacing.dbo.historic_races as races on races.race_id = runners.race_id 
inner join (
    select ru.runner_id, count(*) as wins
    FROM dbHorseRacing.dbo.historic_runners as ru
    inner join dbHorseRacing.dbo.historic_races as ra on ra.race_id = ru.race_id 
    where ru.runner_id = runners.runner_id
    and ra.meeting_date < races.meeting_date
    and ru.finish_position = 1
    group by ru.runner_id
) w on w.runner_id = runners.runner_id

导致问题的以下两行:

where ru.runner_id = runners.runner_id
        and ra.meeting_date < races.meeting_date

我尝试以其他方式编写此查询,但没有成功,我看到其他人使用嵌套选择,从嵌套选择之外引用标识符......

作为一项原则,我试图做的事情通常是错误的吗?如果是这样,还有其他方法可以实现吗?

我已经尝试找到答案,并且非常感谢任何帮助!

劳拉

4

2 回答 2

2

尝试这个 :

SELECT runners.id, (
    select count(*)
    FROM dbHorseRacing.dbo.historic_races
    where historic_races.runner_id = runners.runner_id
    and historic_races.meeting_date < races.meeting_date
    and ru.finish_position = 1
) wins
FROM dbHorseRacing.dbo.historic_runners as runners
inner join dbHorseRacing.dbo.historic_races as races on races.race_id = runners.race_id 
于 2018-08-20T19:18:42.647 回答
0

下面的查询将起作用,因为您没有共享您的输出,所以我只是编辑了查询可行的版本

SELECT runners.id,  wins
    FROM dbHorseRacing.dbo.historic_runners as runners
    inner join dbHorseRacing.dbo.historic_races as races on races.race_id = runners.race_id 
    inner join (
        select ru.runner_id, count(*) as wins
        FROM dbHorseRacing.dbo.historic_runners as ru
        inner join dbHorseRacing.dbo.historic_races as ra on ra.race_id = ru.race_id 
       where ru.finish_position = 1
        group by ru.runner_id
    ) w on w.runner_id = runners.runner_id
于 2018-08-20T19:24:18.630 回答