Combina due tabelle per un output
Domanda
Dire che ho due tabelle:
KnownHours:
ChargeNum CategoryID Month Hours 111111 1 2/1/09 10 111111 1 3/1/09 30 111111 1 4/1/09 50 222222 1 3/1/09 40 111111 2 4/1/09 50
UnknownHours:
ChargeNum Month Hours 111111 2/1/09 70 111111 3/1/09 40.5 222222 7/1/09 25.5
Devo raggruppare queste ore, ignorando Month, in un'unica tabella di dati in modo che il mio risultato previsto sia il seguente:
ChargeNum CategoryID Hours 111111 1 90 111111 2 50 111111 Unknown 110.5 222222 1 40 222222 Unknown 25.5
Non riesco a capirlo. Qualsiasi aiuto sarebbe molto apprezzato!
EDIT: devo sommare le ore per ogni combinazione ChargeNum / Categoria. Ho aggiornato i dati di esempio per riflettere questo.
Soluzione
Dovrai utilizzare UNION
per combinare i risultati di due query. Nel tuo caso:
SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum
Nota: se si utilizza UNION ALL
come sopra, non è più lento dell'esecuzione delle due query separatamente in quanto non verifica duplicati.
Altri suggerimenti
Nell'output previsto, la somma dell'ultima riga non è corretta, dovrebbe essere 40 in base ai dati nelle tabelle, ma ecco la query:
Select ChargeNum, CategoryId, Sum(Hours)
From (
Select ChargeNum, CategoryId, Hours
From KnownHours
Union
Select ChargeNum, 'Unknown' As CategoryId, Hours
From UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId
Ed ecco l'output:
ChargeNum CategoryId
---------- ---------- ----------------------
111111 1 40
111111 2 50
111111 Unknown 70
222222 1 40
222222 Unknown 25.5
Possiamo fare un passo avanti e dire che voglio solo vedere le righe quando combinate che hanno 50 ore o più ... Ho provato questo, ma ricevo un errore che non riesce a trovare SumHours ...
Select ChargeNum, CategoryId, Sum(Hours) As SumHours
From (
Select ChargeNum, CategoryId, Hours
From KnownHours
Union
Select ChargeNum, 'Unknown' As CategoryId, Hours
From UnknownHours
) As a
WHERE (SumHours>=50)
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId
Quindi ho provato
Select ChargeNum, CategoryId, Sum(Hours) As SumHours
From (
Select ChargeNum, CategoryId, Hours
From KnownHours
Union
Select ChargeNum, 'Unknown' As CategoryId, Hours
From UnknownHours
) As a
WHERE (Hours>=50)
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId
Ma questo non sta dando la somma delle ore su entrambi i tavoli ...