SUM()中的错误结果

时间:2012-07-06 11:10:01

标签: sql sql-server-2000

SQL Server 2000 - 4个表,每个3列。个人ID(COTA),用户(Telegestionador)和工作量值。

表格是:Contactados, NC, FQ, OT

其中一个的例子。

XAV045  QUIPILDORY    26
XAV045  QUIPILDORY    29
XAV045  QUIPILDORY    21
XAV045  QUIPILDORY    39
XAV052  LOPEZRA       29
XAV052  LOPEZRA       39
XAV052  LOPEZRA       24
XAV052  LOPEZRA       36

我需要的是什么。带有ID,USER的结果视图,然后是具有按个人ID /用户分组的工作量总和的字段。 (有4个表,所以在最终视图中我应该有6列)

所以,第一行应该是

XAV045,QUIPILDORY, 115, X, Y, Z

将X,Y,Z作为其他3个表中SUM()的结果。

首先尝试的是:

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

它会抛出错误的结果,我知道GROUP BY将结果分组,而不是单独分组表行。但我找不到合适的方法。

任何帮助?

1 个答案:

答案 0 :(得分:1)

假设所有四个表都具有相同的四列数据类型,您可以使用union all列出所有值,然后将它们作为子查询的一部分求和:

SELECT
COTA
,Telegestionador
,SUM(CASE WHEN table_name = 'Contactados' THEN work_value ELSE 0 END) AS Contactados_sum
,SUM(CASE WHEN table_name = 'NC' THEN work_value ELSE 0 END) AS nc_sum
,SUM(CASE WHEN table_name = 'FQ' THEN work_value ELSE 0 END) AS fq_sum
,SUM(CASE WHEN table_name = 'QT' THEN work_value ELSE 0 END) AS qt_sum
FROM
(
SELECT 
COTA
,Telegestionador
,work_value
,'Contactados' as table_name
FROM Contactados
UNION ALL
SELECT 
COTA
,Telegestionador
,work_value
,'NC' as table_name
FROM NC
UNION ALL
SELECT 
COTA
,Telegestionador
,work_value
,'FQ' as table_name
FROM FQ
UNION ALL
SELECT 
COTA
,Telegestionador
,work_value
,'QT' as table_name
FROM QT
) summary
GROUP BY
COTA
,Telegestionador