1

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、ZSUM()来自其他 3 个表的结果。

第一次尝试是这样的:

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将结果分组,而不是单独的表行。但我找不到这样做的正确方法。

有什么帮助吗?

4

1 回答 1

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
于 2012-07-06T11:21:25.847 回答