Skip to content
Advertisement

UNION ALL not combining rows

I have this table called “valores_indices” where it imports stocks values every 1 hour, I need to get the values from each monitored stock at 8am and 6pm, those being respectively my “vlrAberto” and “vlrFechado” selects I don’t get why these are not merging, I’ve done it before, any help would be appreciated since I’m running out of ideas, I’ve tried to nest it without any luck

SELECT
    i.descricao as cotacao,
    m.quantidade as qtdComprada,
    m.valor as vlrUnitario,
    (m.valor * m.quantidade) as valorCompra,
    v.valor as vlrAberto,
    0 as vlrFechado,
    v.data as data
FROM
    movimento_indices m
    LEFT JOIN indices i ON i.idindice = m.idindice
    LEFT JOIN valores_indices v ON v.idindice = m.idindice
WHERE
    v.hora IN ('08:00')
UNION ALL
SELECT
    i.descricao as cotacao,
    m.quantidade as qtdComprada,
    m.valor as vlrUnitario,
    (m.valor * m.quantidade) as valorCompra,
    0 as vlrAberto,
    v.valor as vlrFechado,
    v.data as data
FROM
    movimento_indices m
    LEFT JOIN indices i ON i.idindice = m.idindice
    LEFT JOIN valores_indices v ON v.idindice = m.idindice
WHERE
    v.hora IN ('18:00')

EDIT

This is what I get

enter image description here

This is the expected result

enter image description here

Advertisement

Answer

I think that you want conditional aggregation here:

SELECT
    i.descricao as cotacao,
    m.quantidade as qtdComprada,
    m.valor as vlrUnitario,
    (m.valor * m.quantidade) as valorCompra,
    MAX(CASE WHEN v.hora = '08:00' THEN v.valor END) as vlrAberto,
    MAX(CASE WHEN v.hora = '18:00' THEN v.valor END) as vlrFechado,
    v.data as data
FROM
    movimento_indices m
    LEFT JOIN indices i ON i.idindice = m.idindice
    LEFT JOIN valores_indices v ON v.idindice = m.idindice
WHERE v.hora IN ('08:00', '18:00')
GROUP BY 
    i.descricao,
    m.quantidade,
    m.valor,
    m.quantidade,
    v.data

Another option is a lateral join:

SELECT
    i.descricao as cotacao,
    m.quantidade as qtdComprada,
    m.valor as vlrUnitario,
    (m.valor * m.quantidade) as valorCompra,
    v.vlrAberto,
    v.vlrFechado,
    v.data as data
FROM
    movimento_indices m
    LEFT JOIN indices i ON i.idindice = m.idindice
    LEFT LATERAL JOIN (
        SELECT 
            MAX(v.valor) FILTER(WHERE v.hora = '08:00') as vlrAberto,
            MAX(v.valor) FILTER(WHERE v.hora = '18:00') as vlrFechado,
            v.data
        FROM valores_indices v
        WHERE v.idindice = m.idindice AND v.hora IN ('08:00', '18:00')
        GROUP BY v.data
    ) v ON 1 = 1
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement