将子查询存储在变量中

时间:2019-03-05 14:40:48

标签: tsql

我在下面有这个查询,我需要在两列之间进行减法:SM&L。 问题是SM&L是一个子查询...我试图将这些子查询存储在变量中,但是不起作用...

SELECT 
[STORE] = ET2.ET_LIBELLE ,
[SELLER] = GCL5.GCL_LIBELLE,

(SELECT
    COUNT(DISTINCT GL_NUMERO)

FROM GCLIGNEARTDIM

LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL 

WHERE

AND ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC < 200

) S,

(SELECT
    COUNT(DISTINCT GL_NUMERO)

FROM GCLIGNEARTDIM

LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL 

WHERE 

AND ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC > 200
) 'M&L'

FROM GCLIGNEARTDIM

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

GL_DATEPIECE = '2019-02-28'

GROUP BY
ET2.ET_LIBELLE,
GCL5.GCL_LIBELLE

1 个答案:

答案 0 :(得分:1)

如果您使用的是Microsoft SQL,那么执行此操作的一种方法是使用CTE。我没有任何测试数据,所以我只是重新发布您的查询(WHERE子句存在一些问题需要解决)

WITH cteData AS
(
    SELECT  [STORE] = ET2.ET_LIBELLE 
            , [SELLER] = GCL5.GCL_LIBELLE
            , (
                SELECT  COUNT(DISTINCT GL_NUMERO)
                FROM    GCLIGNEARTDIM
                        LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
                        LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL 
                WHERE   ET4.ET_LIBELLE = ET2.ET_LIBELLE
                        AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
                        AND GP_TOTALTTC < 200
            ) S
            , (
                SELECT  COUNT(DISTINCT GL_NUMERO)
                FROM    GCLIGNEARTDIM
                        LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
                        LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL 
                WHERE   ET4.ET_LIBELLE = ET2.ET_LIBELLE
                        AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
                        AND GP_TOTALTTC > 200
            ) 'M&L'
    FROM    GCLIGNEARTDIM
            LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT 
            LEFT OUTER JOIN COMMERCIAL GCL5 ON GL_REPRESENTANT=GCL5.GCL_COMMERCIAL 
    WHERE   GL_DATEPIECE = '2019-02-28'
    GROUP BY ET2.ET_LIBELLE, GCL5.GCL_LIBELLE
)
SELECT  *
        , ([S] - [M&L]) AS [S minus M&L]
FROM    cteData