不确定这是否是最好的方法,但我会尝试举例解释我想要完成的事情。我有大约4或5个不同的表,每个表包含一个TOTAL
字段。一个表包含CUSTOMER_ID
(其中4个或5个表中的每个表都包含一个将其记录链接到父CUSTOMER
表的外键)。
我希望在查询的一列中按CUSTOMER_ID
进行分组,而其他每列都包含相应表格的总计。
这有意义吗?我正在寻找最有效和设计合理的查询。听起来我需要子查询而不是一堆左外连接?
答案 0 :(得分:3)
SELECT C.CUSTOMER_ID,
T1.TOTAL TOTAL_T1,
T2.TOTAL TOTAL_T2,
T3.TOTAL TOTAL_T3,
T4.TOTAL TOTAL_T4,
T5.TOTAL TOTAL_T5
FROM CUSTOMER C
LEFT JOIN ( SELECT CUSTOMER_ID, SUM(TOTAL) TOTAL)
FROM TABLE1
GROUP BY CUSTOMER_ID) T1
ON C.CUSTOMER_ID = T1.CUSTOMER_ID
LEFT JOIN ( SELECT CUSTOMER_ID, SUM(TOTAL) TOTAL)
FROM TABLE2
GROUP BY CUSTOMER_ID) T2
ON C.CUSTOMER_ID = T2.CUSTOMER_ID
LEFT JOIN ( SELECT CUSTOMER_ID, SUM(TOTAL) TOTAL)
FROM TABLE3
GROUP BY CUSTOMER_ID) T3
ON C.CUSTOMER_ID = T3.CUSTOMER_ID
LEFT JOIN ( SELECT CUSTOMER_ID, SUM(TOTAL) TOTAL)
FROM TABLE4
GROUP BY CUSTOMER_ID) T4
ON C.CUSTOMER_ID = T4.CUSTOMER_ID
LEFT JOIN ( SELECT CUSTOMER_ID, SUM(TOTAL) TOTAL)
FROM TABLE5
GROUP BY CUSTOMER_ID) T5
ON C.CUSTOMER_ID = T5.CUSTOMER_ID
答案 1 :(得分:0)
不确定我是否正确地得到了你想要的东西,但我认为你可以用简单的连接来完成这个,对于两个表
select table1.customerId, sum(table1.total) as total1, sum(table2.total) as total2
FROM table1, table2
where table1.customerId=table2.customerId
group by table1.customerId;
您可以根据需要使用任意数量的表格
答案 2 :(得分:0)
这是另一种可能性。它不需要派生任何表格然后加入它们。这应该也足够有效,假设table1-table5上的FK是CUSTOMER_ID ......虽然不是100%肯定。另外根据我离开加入时的经验,使用ISNULL通常是一个好主意,所以你总是得到一些数值(尽管在这种情况下,这是我的另一个假设)。希望这有帮助!
SELECT
C.CUSTOMER_ID,
ISNULL(SUM(T1.TOTAL), 0) AS TOTAL_T1,
ISNULL(SUM(T2.TOTAL), 0) AS TOTAL_T2,
ISNULL(SUM(T3.TOTAL), 0) AS TOTAL_T3,
ISNULL(SUM(T4.TOTAL), 0) AS TOTAL_T4,
ISNULL(SUM(T5.TOTAL), 0) AS TOTAL_T5
FROM CUSTOMER C
LEFT JOIN TABLE1 T1 ON C.CUSTOMER_ID = T1.CUSTOMER_ID
LEFT JOIN TABLE2 T2 ON C.CUSTOMER_ID = T2.CUSTOMER_ID
LEFT JOIN TABLE3 T3 ON C.CUSTOMER_ID = T3.CUSTOMER_ID
LEFT JOIN TABLE4 T4 ON C.CUSTOMER_ID = T4.CUSTOMER_ID
LEFT JOIN TABLE5 T5 ON C.CUSTOMER_ID = T5.CUSTOMER_ID
GROUP BY C.CUSTOMER_ID