Aggiunta contenuto della colonna in una query SQL UNION
Domanda
Finora ho questa query
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
Il mio obiettivo è quello di UNION queste due query aggiungono le colonne SUM 'ITEM_COUNT' foreach code_desc. È possibile?
Soluzione
Senza ulteriori informazioni sui codici, come se è possibile che i codici si escludono a vicenda tra le due tabelle, l'uso:
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
Altri suggerimenti
Si, facendo qualcosa di simile
SELECT Sum(unionedTable.item_count)
FROM
(
//your query
) as unionedTable
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow