选择返回超过1个值的Where子句中的Statement

时间:2014-07-25 14:50:09

标签: sql sql-server select sql-server-2012

我正在使用SQL Server 2012编写过程,并且在尝试运行此select语句时收到此错误。

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我认为这与Select条款中的where声明有关,但我不太确定。

程序:

select top 100  
   Team.ID,
   Team.Name,
   sum(Results.Points) as PointsTotal
from            
   Results
inner join 
   Teamon Results.TeamID = Team.ID
where           
   Results.TeamID = Team.ID
   and Results.Date > DATEADD(YY, -1, GETDATE())
   and Results.Date <> (Select Min(Date)
                        from Results
                        Inner join Competition on Competition.ID = Results.CompetitionID
                        Inner join Team on Team.ID = Results.TeamID
                        where CompetitionID = 3
                          and TeamID = Team.ID
                          and Date > (DATEADD(YY, -1, GETDATE()))
                        group by Team.Name
                        Having Count(Competition.ID) > 1)
group by        
    Team.ID, Team.Name
order by        
    PointsTotal desc

3 个答案:

答案 0 :(得分:2)

如果子查询可能返回多个结果,则应将<>运算符替换为not in

答案 1 :(得分:2)

由于WHERE子句按Team.Name分组并选择MIN(日期),因此您将返回每个团队的最小日期(基于其他条件)。如果您使用&lt;&gt;运算符只能在该运算符的另一侧有一个值,如果需要多个值,请使用NOT IN运算符。

如果您需要各个团队与最小日期匹配,我将LEFT JOIN连接到TeamId和MinimumDate上的子查询,然后在WHERE子句中我将确保您加入的其中一个字段IS NULL(表示连接条件与子查询不匹配,并且将过滤掉该团队的任何记录和最小日期)。查询看起来像这样:

select top 100  Team.ID,
                Team.Name,
                sum(Results.Points) as PointsTotal
from            Results
inner join Team on Results.TeamID = Team.ID
left join (
      Select    Team.Id, Min(Date) AS MinDate
      from  Results
      Inner join Competition on Competition.ID = Results.CompetitionID
      Inner join Team on Team.ID = Results.TeamID
      where CompetitionID = 3
      and   TeamID = Team.ID
      and   Date > (DATEADD(YY, -1, GETDATE()))
      group by  Team.ID
      Having    Count(Competition.ID) > 1
  ) MinimumDateQuery ON
  Results.TeamID = MinimumDateQuery.Id AND
  Results.Date = MinimumDateQuery.MinDate

where           Results.Date > DATEADD(YY, -1, GETDATE())
and             MinimumDateQuery.Id IS NULL
group by        Team.ID, Team.Name
order by        PointsTotal desc

答案 2 :(得分:0)

子查询中的group by将使其返回包含Date的每个值的最小值Team.Name的一行。

简单地考虑一下:

|----------------------|
| Name     | Date      |
|----------------------|
|A         |2001-01-01 |
|A         |2001-01-02 |
|B         |2001-01-01 |
|B         |2001-01-02 |
|C         |2001-01-02 |

执行查询

SELECT MIN(Date) FROM Results GROUP BY Name 

返回

|----------------------|
| No column name       |
|----------------------|
|2001-01-01            |
|2001-01-01            |
|2001-01-02            |