【问题标题】:nested select - multi part identifier not bound error嵌套选择 - 多部分标识符未绑定错误
【发布时间】:2019-01-26 23:00:03
【问题描述】:

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

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

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

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

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

劳拉

【问题讨论】:

  • 如何在子查询中获取跑步者和比赛?
  • 你想要一种运行总和。对于每个 runners.id 和比赛,他在以前的比赛中赢得了多少次?
  • 没错!流动总和。
  • Zaynul - 这就是我似乎无法解决的问题......
  • 何时使用关联子查询,因为您可以在子查询内部使用外部查询,但在这里您只使用子查询

标签: sql sql-server tsql nested-select


【解决方案1】:

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

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

【讨论】:

  • 谢谢 Zaynul,我刚刚实现了 Daniel 的版本,但谢谢。 :)
【解决方案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 

【讨论】:

  • 非常感谢丹尼尔,我刚刚尝试过,效果很好!再次感谢,我为此浪费了很多时间。
猜你喜欢
  • 2020-06-16
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多