【问题标题】:SQL issue - The column 'Id' was specified multiple times for 'sv2017'SQL 问题 - 为“sv2017”多次指定了“Id”列
【发布时间】:2020-07-13 13:46:45
【问题描述】:

我不断收到错误消息

消息 8156,第 16 级,状态 1,第 5 行
为“sv2017”多次指定了“Id”列。

消息 8156,第 16 层,状态 1,第 7 行
为“sv2010”多次指定了“Id”列。

使用以下脚本:

select 
    sv2017.id, sv2017.TotalArea, sv2017.uarn, 
    sv2010.id, sv2010.PlantMachineryValue, sv2017.PlantMachineryValue, 
    sv2010.uarn, sv2017.BAReferenceNumber 
from 
    (select * 
     from summaryvaluation sv 
     join SummaryValuationPlant svp on sv.id = svp.SummaryValuationId  
     where sv.yearid = 2 
       and sv.id in (select id /*Get the most recent valuation for the list year*/
                     from
                         (select 
                              id, uarn, 
                              rank() over (partition by uarn order by fromdate desc) as RankOrder 
                          from 
                              summaryvaluation 
                          where 
                              yearid = 2 and systemactive = 1) tbl
                     where 
                         rankorder = 1)) sv2017
left outer join 
    (select * 
     from summaryvaluation sv2 
     join SummaryValuationPlant svp2 on sv2.id = svp2.SummaryValuationId 
     where sv2.yearid = 1 
       and sv2.id in (select id /*Get the most recent valuation for the list year*/
                      from
                          (select 
                               id, uarn, 
                               rank() over (partition by uarn order by fromdate desc) as RankOrder 
                           from 
                               summaryvaluation 
                           where 
                               yearid = 1 and systemactive = 1) tbl
                      where 
                          rankorder = 1)) sv2010 on sv2017.uarn = sv2010.uarn
where
    isnull (sv2017.PlantMachineryValue, 0) > isnull(sv2010.PlantMachineryValue, 0)

而且我看不出哪里出错了!这可能很明显,我的大脑无法正常工作,但感谢您提供任何帮助。

谢谢

【问题讨论】:

  • 错误很明显
  • 这只是为什么你不应该只是“拍”SELECT * 的原因之一。显然,summaryvaluationSummaryValuationPlant 表都有一个列id,因此SELECT(在子查询中)将返回id 列和id 列;你看到那里的问题了吗?
  • 使用别名,例如T1.id As Foo, T2.id As Bar SQL Server 需要知道你指的是哪个id

标签: sql-server primary-key


【解决方案1】:

你的问题可能在这里:

select * 
     from summaryvaluation sv 
     join SummaryValuationPlant svp 

该代码出现在 2 个不同的地方(具有不同的别名)。无论如何,我怀疑两个表都有一个 id 列,所以当你在派生表中使用它时,SQL 不知道你是从 sv 表还是 svp 表中引用一个。

要更正此问题,请删除 * 并仅列出您将在较大查询中的其他地方使用的那些列。

【讨论】:

  • 不客气。坚持下去,我相信你的 SQL 技能会有所提高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 2017-06-03
  • 1970-01-01
相关资源
最近更新 更多