[英]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![]() |
AccountNo![]() |
---|---|
331 ![]() |
AccountNo1![]() |
332 ![]() |
AccountNo2 ![]() |
333 ![]() |
AccountNo2 ![]() |
334 ![]() |
AccountNo2 ![]() |
The activity table looks like this:活动表如下所示:
CustID![]() |
ActivityID![]() |
Month![]() |
Sales![]() |
---|---|---|---|
331 ![]() |
331133 ![]() |
Jan-21 ![]() |
£30 ![]() |
332 ![]() |
331101 ![]() |
Jan-21 ![]() |
£10 ![]() |
332 ![]() |
331121 ![]() |
Feb-21 ![]() |
£40 ![]() |
332 ![]() |
331196 ![]() |
Feb-21 ![]() |
£40 ![]() |
332 ![]() |
331141 ![]() |
Mar-21 ![]() |
£40 ![]() |
333 ![]() |
331120 ![]() |
Feb-21 ![]() |
£20 ![]() |
334 ![]() |
331119 ![]() |
Mar-21 ![]() |
£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.