内部联接两个表的汇总列值

时间:2018-06-29 21:35:44

标签: sql-server join

假设我有两个表:[ReceivingLog]和[Customer_Event]。请参阅下表。

登录

     logId    eventId    customerId    pmCount    pmWeight
       1       1411       4196            1         14
       2       1411       4196            2         14
       3       1411       4198            1         14
       4       1411       4198            1         11
       5       1411       4196            3         10

Customer_Event

     customerId    eventId
       4196         1411 
       4198         1411
       4199         1411

我想得到这种结果

     customerId    pmCount    pmWeight
       4196           6          38 
       4198           2          25 
       4199           0           0 

我在下面尝试了此查询,但是我得到了重复的行

SELECT [Log].customerId, [Log].pmCount, [Log].pmWeight
FROM [Log] INNER JOIN [Customer_Event] ON [Log].eventId = [Customer_Event].eventId
WHERE [Log].eventId = 1411

我应该使用哪个查询来获得预期的结果?

3 个答案:

答案 0 :(得分:4)

尝试一下,我输入了一些示例数据并进行了尝试,效果很好:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

答案 1 :(得分:3)

我认为这会有效,未经测试。

change

答案 2 :(得分:1)

尝试一下

Select c.CustomerID, ISNULL(sum(l.pmCount),0), ISNULL(sum(l.pmWeight),0)
from #Customer_Event c
    left join #ReceivingLog l on c.eventId = l.eventID and c.customerId = l.customerId
group by c.CustomerID