SQL隐藏空值并使用union连接结果

时间:2016-01-29 18:48:46

标签: sql-server

我怎样才能加入"结果,避免重复?就像一个不同的功能。我使用的是Microsoft sql server studio

enter image description here

查询:

 SELECT
         CLI.NUMERO as Contaa
        ,CLI.NOME as NOMEe
        ,COUNT(DISTINCT CA.Numero) as cartCriados
        ,NULL as TotQTD
    FROM Clientes as CLI
    LEFT JOIN Cartoes (nolock) as CA ON CA.Cliente=CLI.NUMERO
    LEFT JOIN VendasPOS_Cabecalhos (nolock) as VPC ON VPC.CLIENTE=CLI.NUMERO
    LEFT JOIN VendasPOS_Linhas (nolock) as VPL ON VPL.PRENUMERO=VPC.PRENUMERO
    WHERE CLI.NUMERO LIKE '2119%'
    GROUP BY CLI.NUMERO, CLI.NOME
    UNION ALL
    SELECT
         CLI.NUMERO as Contaa
        ,CLI.NOME as NOMEe
        ,NULL as cartCriados
        ,Sum(ln.qtd) as TotQTD
    from CB_VendasPOS (nolock) as VPCB
    right outer join VendasPOS_Linhas (nolock) as LN on (Ln.AutoReg=VPCB.AutoReg)
    join VendasPOS_Cabecalhos (nolock) as Cab ON (ln.prenumero=cab.prenumero)
    join Clientes (nolock) as Cli on Cli.numero=cab.cliente
    join VendasPOS_Turnos (nolock) as tu on (tu.codturnoauto=cab.codturnoauto)
    right outer join cartoes_mov (nolock) as cm on cm.prenumero=cab.prenumero
    where cab.data>='2015-01-01 00:00:00' and cab.data<='2015-01-30 00:00:00'
    and cm.tipocrt='D'
    group by CLI.NUMERO, cli.nome
    ORDER BY CLI.NUMERO

1 个答案:

答案 0 :(得分:2)

如果不修改您的查询,您可以按键(ContaaNOMEe)进行分组,并获取可以为空的字段MAX()

SELECT Contaa, NOMEe, MAX(cartCriados), MAX(TotQTD)
FROM
    (SELECT
         CLI.NUMERO as Contaa
        ,CLI.NOME as NOMEe
        ,COUNT(DISTINCT CA.Numero) as cartCriados
        ,NULL as TotQTD
    FROM Clientes as CLI
    LEFT JOIN Cartoes (nolock) as CA ON CA.Cliente=CLI.NUMERO
    LEFT JOIN VendasPOS_Cabecalhos (nolock) as VPC ON VPC.CLIENTE=CLI.NUMERO
    LEFT JOIN VendasPOS_Linhas (nolock) as VPL ON VPL.PRENUMERO=VPC.PRENUMERO
    WHERE CLI.NUMERO LIKE '2119%'
    GROUP BY CLI.NUMERO, CLI.NOME
    UNION ALL
    SELECT
         CLI.NUMERO as Contaa
        ,CLI.NOME as NOMEe
        ,NULL as cartCriados
        ,Sum(ln.qtd) as TotQTD
    from CB_VendasPOS (nolock) as VPCB
    right outer join VendasPOS_Linhas (nolock) as LN on (Ln.AutoReg=VPCB.AutoReg)
    join VendasPOS_Cabecalhos (nolock) as Cab ON (ln.prenumero=cab.prenumero)
    join Clientes (nolock) as Cli on Cli.numero=cab.cliente
    join VendasPOS_Turnos (nolock) as tu on (tu.codturnoauto=cab.codturnoauto)
    right outer join cartoes_mov (nolock) as cm on cm.prenumero=cab.prenumero
    where cab.data>='2015-01-01 00:00:00' and cab.data<='2015-01-30 00:00:00'
    and cm.tipocrt='D'
    group by CLI.NUMERO, cli.nome
    ORDER BY CLI.NUMERO) t
GROUP BY t.Contaa, t.NOMEe

你可能最好不要重构查询,所以它只是一个SELECT但是......我对它进行了一次尝试,但是很难说它是否真的会改善它的价值,特别是没有看到一些源数据要测试。