尝试使用INNER JOIN和GROUP BY SQL与SUM函数,不工作

时间:2014-04-12 13:39:16

标签: sql select join group-by inner-join

我没有理解这一点,并想知道是否有人可以帮助我。

我有2个名为RES_DATAINV_DATA

的表

RES_DATA包含我的客户,如下所示

CUSTOMER ID | NAME

1, Robert
2, John
3, Peter

INV_DATA包含下面的INVOICES

INVOICE ID | CUSTOMER ID | AMOUNT

100, 1, £49.95
200, 1, £105.95
300, 2, £400.00
400, 3, £150.00
500, 1, £25.00

我正在尝试写一个SELECT语句,它会给我如下的结果。

CUSTOMER ID | NAME | TOTAL AMOUNT

1, Robert, £180.90
2, John, £400.00
3, Peter, £150.00

我想我需要2个INNER JOINS以某种方式添加INVOICES表的表和SUM值BY GROUP BY Customer Table但老实说认为我遗漏了一些东西。甚至无法接近我需要的结果。

5 个答案:

答案 0 :(得分:19)

这应该有用。

SELECT a.[CUSTOMER ID], a.[NAME], SUM(b.[AMOUNT]) AS [TOTAL AMOUNT]
FROM RES_DATA a INNER JOIN INV_DATA b
ON a.[CUSTOMER ID]=b.[CUSTOMER ID]
GROUP BY a.[CUSTOMER ID], a.[NAME]

我使用SQL Fiddle对SQL Server 2008进行了测试:http://sqlfiddle.com/#!3/1cad5/1

基本上这里发生的是,由于连接,你在“右”(即RES_DATA表)上为“右”的每一行(即{{}获得相同的行1}} table)具有相同的INV_DATA值。当您仅按左侧的列进行分组,然后从右侧执行仅[CUSTOMER ID]列的总和时,它会保持左侧的一行完整,并汇总来自左侧的匹配值右边。

答案 1 :(得分:6)

两种方法......

GROUP BY

SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME

OVER

SELECT RES.[CUSTOMER ID], RES,NAME, 
       SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]

答案 2 :(得分:0)

使用子查询

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

答案 3 :(得分:0)

如果除了组中的列之外还需要检索其他列,则可以考虑以下查询。一次检查它是否运行良好。

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

答案 4 :(得分:-2)

SELECT RES.[CUSTOMER ID], RES.NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA
JOIN INV_DATA ON RES.[CUSTOMER ID]=INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES.NAME