SQL Server 2000 – 4 tables, 3 columns each. Personal ID (COTA), User (Telegestionador), and an amount-of-work value.
Tables are: Contactados, NC, FQ, OT
Example of one of them.
XAV045 QUIPILDORY 26
XAV045 QUIPILDORY 29
XAV045 QUIPILDORY 21
XAV045 QUIPILDORY 39
XAV052 LOPEZRA 29
XAV052 LOPEZRA 39
XAV052 LOPEZRA 24
XAV052 LOPEZRA 36
What I need is. A result-view with ID, USER and then the fields with the sum of the amount of work grouped by personal id/user. (there are 4 tables, so in the final view I should have 6 columns)
So, first row should be
XAV045,QUIPILDORY, 115, X, Y, Z
Being X, Y, Z the results of SUM() from the other 3 tables.
First try is this:
SELECT
dbo.Contactados.COTA, dbo.Contactados.telegestionador,
SUM(dbo.Contactados.Total) AS Total,
SUM(dbo.OT.Total) AS [Cont-Der],
SUM(dbo.FQ.FQ) AS Cerrados,
SUM(dbo.NC.Total) AS NC
FROM
dbo.Contactados
LEFT OUTER JOIN
dbo.OT ON dbo.Contactados.COTA = dbo.OT.COTA AND dbo.Contactados.telegestionador = dbo.OT.telegestionador AND dbo.Contactados.FGfin = dbo.OT.FGfin
LEFT OUTER JOIN
dbo.FQ ON dbo.Contactados.COTA = dbo.FQ.COTA AND dbo.Contactados.telegestionador = dbo.FQ.telegestionador AND dbo.Contactados.FGfin = dbo.FQ.FGfin
LEFT OUTER JOIN
dbo.NC ON dbo.Contactados.COTA = dbo.NC.COTA AND dbo.Contactados.telegestionador = dbo.NC.telegestionador AND dbo.Contactados.FGfin = dbo.NC.FGfin
GROUP BY
dbo.Contactados.telegestionador, dbo.Contactados.COTA
It throws wrong results, I know GROUP BY groups the results, not the table rows individually. But I can’t find the proper way to do so.
Any help?
Assuming that all four tables have identical datatypes for the four columns, you can use a union all to list all values, and then sum those as part of a subquery: