子查询返回的值不止1个-Multuple错误消息

时间:2019-03-04 12:21:52

标签: sql

我在下面有此代码,我收到了此错误:子查询返回了多个值..如您所见,我正在使用导致此问题的子查询。

该怎么办?请帮助我解决此问题。

    SELECT 
    [MAGASIN] = ET2.ET_LIBELLE ,
    [CA]= sum(GL_MONTANTTTC),
    [NBR TICKET] = count(distinct GL_NUMERO),

    (SELECT
    [NBR TICKET] = count(distinct GL_NUMERO)

    FROM GCLIGNEARTDIM 

LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT 
    LEFT OUTER JOIN COMMERCIAL GCL3 ON GL_REPRESENTANT=GCL3.GCL_COMMERCIAL 
    WHERE (GL_DATEPIECE >= '20190228 00:00:00' AND GL_DATEPIECE < '20190301 00:00:00' 
    AND (GCL3.GCL_LIBELLE='vendeur x'))
    AND GL_ETABLISSEMENT in ('W01','W05','F10')

    GROUP BY
    ET2.ET_LIBELLE

    )AS 'VENDEUR X'

    FROM GCLIGNEARTDIM 

LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT  
    LEFT OUTER JOIN COMMERCIAL GCL3 ON GL_REPRESENTANT=GCL3.GCL_COMMERCIAL 


    WHERE (GL_DATEPIECE >= '20190228 00:00:00' AND GL_DATEPIECE < '20190301 00:00:00'
    AND GL_ETABLISSEMENT in ('W01','W05','F10')

    GROUP BY
    ET2.ET_LIBELLE

    ORDER BY
    ET2.ET_LIBELLE

1 个答案:

答案 0 :(得分:0)

您的代码可以使用一些重新格式化以提高可读性。如果人们可以快速轻松地消化您的问题和代码,则您更有可能获得高质量的答案。另外,外部查询的WHERE子句中还有一个额外的开放括号。

使用子查询时,应避免使用与外部查询相同的表别名。使用唯一的别名。

您遇到的问题是由产生列VENDEUR X的子查询引起的。要使子查询正常工作,执行时只需要返回一行即可。在您的情况下,它返回多行并抛出错误消息。

要解决此问题,请独立运行子查询并检查返回的数据。您正在对具有多个值的ET2.ET_LIBELLE列进行分组。根据我想您要尝试执行的操作,应将ET2.ET_LIBELLE添加到WHERE子句中。参见下面的示例。

SELECT 
    [MAGASIN] = ET2.ET_LIBELLE,
    [CA]= SUM(GL_MONTANTTTC),
    [NBR TICKET] = COUNT(DISTINCT GL_NUMERO),
    (
        SELECT [NBR TICKET] = COUNT(DISTINCT GL_NUMERO) 
        FROM 
            GCLIGNEARTDIM 
            LEFT OUTER JOIN ETABLISS ETI ON GL_ETABLISSEMENT=ETI.ET_ETABLISSEMENT 
            LEFT OUTER JOIN COMMERCIAL GCLI ON GL_REPRESENTANT=GCLI.GCL_COMMERCIAL 
        WHERE 
            (
                GL_DATEPIECE >= '20190228 00:00:00' 
                AND GL_DATEPIECE < '20190301 00:00:00' 
                AND (GCL3.GCL_LIBELLE='vendeur x')
            )
            AND GL_ETABLISSEMENT IN ('W01','W05','F10')
            AND ETI.ET_LIBELLE = ET2.ET_LIBELLE
    ) AS 'VENDEUR X'
FROM 
    GCLIGNEARTDIM 
    LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT  
    LEFT OUTER JOIN COMMERCIAL GCL3 ON GL_REPRESENTANT=GCL3.GCL_COMMERCIAL
WHERE 
    GL_DATEPIECE >= '20190228 00:00:00' 
    AND GL_DATEPIECE < '20190301 00:00:00' 
    AND GL_ETABLISSEMENT IN ('W01','W05','F10')
GROUP BY
    ET2.ET_LIBELLE
ORDER BY
    ET2.ET_LIBELLE