SQL Server错误 - 消息116

时间:2016-05-25 19:25:03

标签: sql-server-2014

我的查询如下,并在其中包含一个子查询:

SELECT       
    dbo.Lawsuit.LawsuitNUM, dbo.Lawsuit.LawsuitYear,
    dbo.Groups.GroupName, dbo.LawsuitType.LawsuitType,
    dbo.Courts.CourtName,
    (select 
         LawsuitID, DOJ, NextMeeting, ReceiptNUM, ExportNUM, ExportDate
     from 
         (select   
              dbo.LawsuitExport.LawsuitID, 
              dbo.LawsuitExport.DOJ,
              dbo.LawsuitExport.NextMeeting,
              dbo.LawsuitExport.ReceiptNUM,
              dbo.LawsuitExport.ExportNUM,
              dbo.LawsuitExport.ExportDate,
              row_number() over(partition by dbo.LawsuitExport.LawsuitID 
                                order by dbo.LawsuitExport.ExportDate desc) as rn
          from 
              dbo.LawsuitExport) as T 
       where 
           rn = 1)
FROM    
    dbo.Courts 
INNER JOIN
    dbo.LawsuitType ON dbo.Courts.CourtID = dbo.LawsuitType.CourtID 
INNER JOIN
    dbo.Groups ON dbo.LawsuitType.LawsuitTypeID = dbo.Groups.LawsuitTypeID 
INNER JOIN
    dbo.Lawsuit ON dbo.Groups.GroupID = dbo.Lawsuit.GroupID 
INNER JOIN
    dbo.LawsuitExport ON dbo.Lawsuit.LawsuitID = dbo.LawsuitExport.LawsuitID

我收到的错误是:

  

当未使用EXISTS

引入子查询时,只能在选择列表中指定一个表达式

2 个答案:

答案 0 :(得分:1)

这条线 select LawsuitID,DOJ,NextMeeting,ReceiptNUM,ExportNUM,ExportDate不起作用,因为当尝试在另一个select语句中使用时,只能从子查询返回1个项目。例如

SELECT X FROM Y

SELECT X, (SELECT A,B,C FROM FOO) FROM Y不好

A,B,C无法映射到单个元素,因此无效

答案 1 :(得分:0)

如果那是你的意图,那么考虑修改你的查询,如

SELECT       
    dbo.Lawsuit.LawsuitNUM, dbo.Lawsuit.LawsuitYear,
    dbo.Groups.GroupName, dbo.LawsuitType.LawsuitType,
    dbo.Courts.CourtName,XXX.LawsuitID, XXX.DOJ, XXX.NextMeeting, XXX.ReceiptNUM, XXX.ExportNUM, XXX.ExportDate
FROM    
    dbo.Courts 
INNER JOIN
    dbo.LawsuitType ON dbo.Courts.CourtID = dbo.LawsuitType.CourtID 
INNER JOIN
    dbo.Groups ON dbo.LawsuitType.LawsuitTypeID = dbo.Groups.LawsuitTypeID 
INNER JOIN
    dbo.Lawsuit ON dbo.Groups.GroupID = dbo.Lawsuit.GroupID 
INNER JOIN
    dbo.LawsuitExport ON dbo.Lawsuit.LawsuitID = dbo.LawsuitExport.LawsuitID
INNER JOIN (select   
              LawsuitID, 
              DOJ,
              NextMeeting,
              ReceiptNUM,
              ExportNUM,
              ExportDate,
              row_number() over(partition by LawsuitID 
                                order by ExportDate desc) as rn
          from 
              dbo.LawsuitExport) XXX ON dbo.Lawsuit.LawsuitID = XXX.LawsuitID
WHERE XXX.rn = 1;