Question

Jusqu'à présent, j'ai cette requête

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

Mon but est de UNION ces deux requêtes ajouter SOMME les colonnes « ITEM_COUNT » foreach code_desc. Est-ce possible?

Était-ce utile?

La solution

Sans plus d'informations sur les codes, comme s'il est possible que les codes sont mutuellement exclusifs entre les deux tables, utilisez:

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

Autres conseils

Ouais, faire quelque chose comme ça

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


) as unionedTable
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top