2016-01-29 36 views
2

如何「加入」結果並避免重複?像一個獨特的功能。我使用的是Microsoft SQL Server的工作室SQL隱藏空值並與工會結果加入

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 

回答

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 

你可能會更好的重構查詢,所以它只是雖然......我採取了刺探措施,但很難說它是否真的能夠改善事情的價值,特別是沒有看到一些源數據要測試。

+0

This Works。謝謝:)我試圖在一個選擇中做到這一點,但我似乎無法使它工作 – Enato

+0

是的,我認爲你最終需要加入反對子查詢,在這種情況下,這可能會起作用 - 或者至少如果這項工作足夠好,不值得花費額外的工作。 –