Pergunta

Até agora eu tenho esta consulta

SELECT
    COUNT(f.code_id) as item_count, 
    f.code_desc
FROM 
    foo f
    INNER JOIN foohistory fh ON f.history_id = fh.history_id
WHERE
    MONTH(fh.create_dt) = 6
    AND YEAR(fh.create_dr) = 2010
GROUP BY 
    f.code_desc

    UNION ALL

SELECT
    COUNT(b.code_id) as item_count, 
    b.code_desc
FROM 
    bar b
    INNER JOIN barhistory bh ON b.history_id = bh.history_id
WHERE
    MONTH(bh.create_dt) = 6
    AND YEAR(bh.create_dr) = 2010
GROUP BY 
    b.code_desc

Meu objetivo é união, essas duas consultas adicionam a soma das colunas 'item_count' foreach code_desc. Isso é possível?

Foi útil?

Solução

Sem mais informações sobre os códigos, como se for possível que os códigos sejam mutuamente exclusivos entre as duas tabelas, use:

SELECT x.code_desc,
       SUM(x.item_count)
 FROM (SELECT f.code_desc,
              COUNT(f.code_id) as item_count
         FROM foo f
         JOIN foohistory fh ON f.history_id = fh.history_id
        WHERE MONTH(fh.create_dt) = 6
          AND YEAR(fh.create_dr) = 2010
     GROUP BY f.code_desc
       UNION ALL
       SELECT b.code_desc,
              COUNT(b.code_id) as item_count    
         FROM bar b
         JOIN barhistory bh ON b.history_id = bh.history_id
        WHERE MONTH(bh.create_dt) = 6
          AND YEAR(bh.create_dr) = 2010
     GROUP BY b.code_desc) x
GROUP BY x.code_desc

Outras dicas

Sim, fazendo algo assim

SELECT Sum(unionedTable.item_count)
FROM 
(
//your query 


) as unionedTable
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top