SQL查询 - 重复值+添加的信息

时间:2018-02-16 11:02:40

标签: sql

我需要识别表的重复值,这不是通过countgroup by函数的问题,但我需要在那里添加信息。

CUSTOMERS               TRANSACTIONS    
cust_id cust_code       cust_id    trans_id

1       AB12            2          1
2       B12             3          2
3       AB22            2          3
4       B12             1          4

我需要从表cust_code中找到重复的客户代码(CUSTOMERS),我可以使用查询

select a.cust_code, count(*)
from CUSTOMERS a
group by a.cust_code
having count(*) > 1

第一部分我不知道如何处理是从结果中的表TRANSACTIONS获取数据。

现在cust_code'B12'在表CUSTOMERS中出现两次,应该被表示。我希望在表MAX中添加TRANSACTIONS trans_id值。

这有可能吗?我想结果应该是这样的:

cust_id cust_code   trans_id

2           B12         3
4           B12         0
max trans_id的{​​{1}}为cust_id 23的{​​{1}}为max trans_id(cust_id 4无交易)

我在查找cust_id 4值时也没有问题,虽然我不确定如何保留重复的0条件。

数据库引擎不是100%肯定,但我相信它来自IBM。

提前多多感谢!

4 个答案:

答案 0 :(得分:0)

尝试以下方法......

Select c.*, T.trans from
Select a.cust_code, count(*) from CUSTOMERS a
Group by a.cust_code
Having count(*) > 1) c
Left outer join
(Select cust_code, max(id) as trans from transactions
Group by cust_code) t
On c.cust_id = t.cust_id

答案 1 :(得分:0)

您可以在transactions表中的聚合查询中加入此查询:

SELECT    cust_code, cnt, COALESCE(trans, 0)
FROM      (SELECT   cust_id, cust_code, COUNT(*) AS cnt
           FROM     customers
           GROUP BY cust_code
           HAVING   COUNT(*) > 1) a
LEFT JOIN (SELECT   cust_id, MAX(trans_id) AS trans
           FROM     transactions
           GROUP BY cust_id) b ON a.cust_id = b.cust_id

答案 2 :(得分:0)

使用您的查询的一个解决方案如下:

SELECT 
   c.cust_id,
   c.cust_code,
   COALESCE(tt.max_id, 0)
FROM
(
    select a.cust_code, count(*) cnt
    from CUSTOMERS a
    group by a.cust_code
    having count(*) > 1
) t
JOIN customers c ON c.cust_code = t.cust_code
LEFT JOIN (
    select cust_id, MAX(trans_id) max_id
    from transactions
    group by cust_id
) tt ON c.cust_id = tt.cust_id

dbfiddle demo

答案 3 :(得分:0)

就这样做

 select a.*,ifnull(max(c.trans_id),0) as trans_id from Customer a join
 (select cust_code,count(*) cnt from Customer group by 1 having cnt>1) b
 on a.cust_code=b.cust_code
 left join
 transaction c on a.cust_id=c.cust_id