JOIN的ON子句中带有Count的情况

时间:2019-05-28 12:35:16

标签: sql-server

在JOIN(BB_VENDASDOCUMENTOS VD)内,我需要选择VD.ENTRADASAIDA是'S'还是'E',而实际上我需要的是,如果至少有一个BB_VENDASDOCUMENTOS,其中ENTRADASAIDA ='S',请使用'S',否则为'N'<​​/ p>

当试图计数VD.ENTRADASAIDA ='S'的数值时,我尝试做一个案例,如果大于0,它将使用'S',否则使用'N',但是我遇到错误并且合计不能出现在ON子句中...

SELECT
 CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
                                                  FROM BB_PNRACCOUNTINGS ACC1
                                                  JOIN BB_VENDASDOCUMENTOS VD
                                                    ON ( VD.ACCOUNTING = ACC1.HANDLE
                                                                AND  VD.ENTRADASAIDA = CASE WHEN count(case when VD.ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S'  ELSE 'E'  END
                                                    AND  VD.PESSOA = ACC1.BB_CLIENTE
                                                    AND ( ( VD.CANCELADO = 'N' ) OR (VD.CANCELADO IS NULL) ) )
                                                  LEFT JOIN BB_CLIENTECC CENTROCUSTO
                                                    ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
                                                                  WHERE CENTROCUSTO.DESCRICAO IS NOT NULL

1 个答案:

答案 0 :(得分:0)

您将需要扫描表格两次。一次,用S或E标记每个组,然后仅收集符合条件的记录。我可以通过加入子查询来实现,然后根据条件再次加入。我不确定下面的语法是否100%正确,但是基本概念在那里。

;WITH BB_VENDASDOCUMENTOSCalc AS
(
    SELECT ACCOUNTING,PESSOA,
        ENTRADASAIDACalc = count(case when ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S'  ELSE 'E'  END
    FROM 
        BB_VENDASDOCUMENTOS
    WHERE
        (CANCELADO='N' OR CANCELADO IS NULL)
    GROUP BY 
        ACCOUNTING,
        PESSOA
    )
SELECT
 CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
                                                  FROM BB_PNRACCOUNTINGS ACC1
                                                  JOIN BB_VENDASDOCUMENTOSCalc VD1 ON VD1.ACCOUNTING = ACC1.HANDLE AND VD1.PESSOA = ACC1.BB_CLIENTE
                                                  JOIN BB_VENDASDOCUMENTO VD ON  VD.ACCOUNTING = ACC1.HANDLE AND VD.PESSOA = ACC1.BB_CLIENTE AND VD.ENTRADASAIDA = VD1.ENTRADASAIDACalc
                                                  LEFT JOIN BB_CLIENTECC CENTROCUSTO
                                                    ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
                                                                  WHERE CENTROCUSTO.DESCRICAO IS NOT NULL