SQL-Server:当错误为“子查询返回超过1”时如何调整查询

时间:2016-10-27 16:33:51

标签: sql sql-server sql-server-2008 subquery

我有这个大问题:

SELECT C.CODDIPBILDIP                                       AS CODDIPBIDIRE,
       Isnull(A.NOMEDIPENDEN, '') + ' '
       + Isnull(A.COGNOMDIPEND, '')                         AS DIPENDENTERE,
       Sum(C.SALDBILADIPE)                                  AS NUOVAESPRESS,
       Isnull((SELECT E.DESCRICOMMES
               FROM   ORECOMMESSE D,
                      COMMESSE E
               WHERE  E.CODICECOMMES = D.CODCOMORECOM
                      AND ( D.CODDIPORECOM = C.CODDIPBILDIP )
                      AND ( D.MESEORECOMME = 'Settembre' )
                      AND ( D.ANNOORECOMME = 2016 )), '')   AS COMMESSA,
       Isnull((SELECT F.SALDOBILANC
               FROM   ORECOMMESSE F
               WHERE  ( F.CODDIPORECOM = C.CODDIPBILDIP )
                      AND ( F.MESEORECOMME = 'Settembre' )
                      AND ( F.ANNOORECOMME = 2016 )), NULL) AS SCORPORAZION
FROM   DIPENDENTI A,
       BILANCDIPEND C
WHERE  A.CODICEDIPEND = C.CODDIPBILDIP
       AND ( C.MESEBILADIPE = 'Settembre' )
       AND ( C.ANNOBILADIPE = 2016 )
       AND ( C.CODCONECBIDI NOT IN ( '56102', '56105', '56106' ) )
       AND ( A.CODICEDIPEND NOT IN (SELECT DISTINCT B.CODDIPOREDIP
                                    FROM   ORETOTALDIPE B
                                    WHERE  ( B.MESEOREDIPEN = 'Settembre' )
                                           AND ( B.ANNOOREDIPEN = 2016 )) )
GROUP  BY C.CODDIPBILDIP,
          Isnull(A.NOMEDIPENDEN, '') + ' '
          + Isnull(A.COGNOMDIPEND, '') 

我需要重新安排以避免此错误

  

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

导致主select中的两个子查询返回多个结果。 我不是很擅长处理这些大问题,所以我该如何解决? 我试过LEFT JOINORECOMMESSE与其他人一起但我总是得到空。我尝试使用左连接,因为BILANCDIPEND中的数据可能不在ORECOMMESSE中,但即使没有连接,我也希望得到tem,这就是为什么我尝试使用左连接...但它不起作用。这就是为什么我考虑更复杂的查询但是当子查询返回多个记录时它会失败... 谢谢

更新

感谢 Jerry Ritcey 的建议,我能够写出正确的查询:

select
  D.COGNOMDIPEND as COGNDIPERECO,
  SUM(B.SALDBILADIPE) as BILANCINO,
  A.SALDOBILANC as SALORECOMREC,
  E.DESCRICOMMES as DESCCOMMRECO,
  ISNULL(D.NOMEDIPENDEN, '') + '  ' + ISNULL(D.COGNOMDIPEND, '') as NOMEDIPERECO
from
  (((BILANCDIPEND B  left join  DIPENDENTI D on D.CODICEDIPEND =  B.CODDIPBILDIP and (D.CODICEDIPEND = B.CODDIPBILDIP))
  left join  ORECOMMESSE A on (A.CODDIPORECOM = B.CODDIPBILDIP))
  left join  COMMESSE E on E.CODICECOMMES = A.CODCOMORECOM)
where (B.MESEBILADIPE = 'September')
      and   (B.ANNOBILADIPE = 2016)
      and   (B.CODCONECBIDI NOT IN ('56102','56105','56106'))
      and   (B.CODDIPBILDIP NOT IN (
  select
    C.CODDIPOREDIP
  from
    ORETOTALDIPE C
  where (C.MESEOREDIPEN = 'September')
        and   (C.ANNOOREDIPEN = 2016)))
group by
  A.SALDOBILANC,
  E.DESCRICOMMES,
  ISNULL(D.NOMEDIPENDEN, '') + '  ' + ISNULL(D.COGNOMDIPEND, ''),
  D.COGNOMDIPEND

0 个答案:

没有答案