简体   繁体   English

在 SQL 中只加入一次表

[英]Joining table only once in SQL

I'm sure this is very basic, but I've hit a brick wall.我敢肯定这是非常基本的,但我已经碰壁了。 First post here, long time reader.第一次在这里发帖,老读者。

I've got two tables, one is a list of customers, one is a list of their activity by month.我有两张表,一张是客户列表,一张是他们每月的活动列表。 For some unknown reason, some of the data in the activity column is duplicated and it's causing me errors when calculating totals.由于某些未知原因,活动列中的某些数据重复,导致我在计算总计时出错。 Is there a way for me to only join the data in the activity table once?有没有办法让我只加入活动表中的数据一次?

Eg the customer table:例如客户表:

CustID客户 ID AccountNo户口号码
331 331 AccountNo1帐号1
332 332 AccountNo2 AccountNo2
333 333 AccountNo2 AccountNo2
334 334 AccountNo2 AccountNo2

The activity table looks like this:活动表如下所示:

CustID客户 ID ActivityID活动ID Month Sales销售量
331 331 331133 331133 Jan-21 1月21日 £30 30 英镑
332 332 331101 331101 Jan-21 1月21日 £10 10 英镑
332 332 331121 331121 Feb-21 2月21日 £40 40 英镑
332 332 331196 331196 Feb-21 2月21日 £40 40 英镑
332 332 331141 331141 Mar-21 3月21日 £40 40 英镑
333 333 331120 331120 Feb-21 2月21日 £20 20 英镑
334 334 331119 331119 Mar-21 3月21日 £20 20 英镑

You will see there are two rows for customer 332 for Feb-21 with the same sales amount.您将看到 2 月 21 日的客户 332 有两行销售额相同。 Total sales for customer 332 are £90 not £130.客户 332 的总销售额为 90 英镑而不是 130 英镑。 How do I tell the JOIN to ignore multiple rows for a particular month if duplicated?如果重复,我如何告诉 JOIN 忽略特定月份的多行?

At the moment I'm doing a basic:目前我正在做一个基本的:

JOIN Activity AC (NOLOCK) ON C.CUSTID = AC.CUSTID

Obviously moving forward the activity table needs fixing but I'm hoping for a quick win!显然,活动表需要修复,但我希望快速获胜!

Sorry if this is basic!对不起,如果这是基本的! Mark标记

One method is:一种方法是:

select c.*, a.*
from customer c left join
     (select a.*,
             row_number() over (partition by custid, month order by amount) as seqnum
      from activity a
     ) a
     on c.custid = a.custid and c.seqnum = 1;

It is unclear if the amounts need to be the same for the duplication.目前尚不清楚复制的金额是否需要相同。 If so, include amount in the partition by .如果是这样,请在partition by中包含amount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM