Join SQL SERVER Selects

Asked

Viewed 47 times

3

I have the following selects, but need to be returned these data together, joining the selects someone suggests something?

SELECT 
COUNT(numero_parcela) as 'total_parcelas',
SUM(valor_original) as 'valor_original', 
SUM(valor_pago) as 'valor_pago' 
FROM financeiro.contas_receber 
WHERE id_cliente = 247

SELECT 
COUNT (numero_parcela) as 'parcelas_atraso', 
SUM(valor_original) as 'valor_atraso'
FROM financeiro.contas_receber
WHERE id_cliente = 247 and data_vencimento < GETDATE()

from now on thank

1 answer

2

You can use the two options below, I would use the first option as it is the same table, thus avoiding unnecessary processing:

CASE WHEN:

SELECT 
    COUNT(numero_parcela) as 'total_parcelas',
    SUM(valor_original) as 'valor_original', 
    SUM(valor_pago) as 'valor_pago',
    SUM(CASE WHEN data_vencimento < GETDATE() THEN valor_origianl ELSE 0 END) as 'valor_atraso'
FROM financeiro.contas_receber 
WHERE id_cliente = 247

CROSS JOIN:

SELECT 
    COUNT(a.numero_parcela) as 'total_parcelas',
    SUM(a.valor_original) as 'valor_original', 
    SUM(a.valor_pago) as 'valor_pago',
    b.parcelas_atraso,
    b.valor_atraso
FROM financeiro.contas_receber as a
CROSS JOIN (
    SELECT 
        COUNT (numero_parcela) as 'parcelas_atraso', 
        SUM(valor_original) as 'valor_atraso'
    FROM financeiro.contas_receber
    WHERE id_cliente = 247 and data_vencimento < GETDATE()
) as b
WHERE a.id_cliente = 247
  • you gave me the way! , I’ll just make some adjustments and I believe it will work out! very thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.