Sql 有条件复制

Sql 有条件复制,sql,presto,Sql,Presto,我想获得每个商户id的商品id的副本数量,其中邮政编码不相同。请参见下面的示例: 表格 merchant_id article_id zip_code 1 4555 1000 1 4555 1003 1 4555 1002 1 3029 1000 2 7539 10

我想获得每个
商户id
商品id
的副本数量,其中
邮政编码不相同。请参见下面的示例:

表格

merchant_id     article_id   zip_code 
1               4555         1000
1               4555         1003
1               4555         1002
1               3029         1000
2               7539         1005
2               7539         1005
2               7539         1002
2               1232         1006
3               5555         1000
3               5555         1001
3               5555         1002
3               5555         1003
merchant_id     count_duplicate
1                3
2                2
3                4
输出表

merchant_id     article_id   zip_code 
1               4555         1000
1               4555         1003
1               4555         1002
1               3029         1000
2               7539         1005
2               7539         1005
2               7539         1002
2               1232         1006
3               5555         1000
3               5555         1001
3               5555         1002
3               5555         1003
merchant_id     count_duplicate
1                3
2                2
3                4
这是我当前使用的查询,但我很难包含邮政编码条件:

SELECT merchant_id
       ,duplicate_count
FROM main_table mt 
JOIN(select article_id, count(*) AS duplicate_count
     from main_table
     group by article_id
     having count(article_id) >1) mt_1
ON mt.article_id ON mt_1.article_id = mt.article_id


如果我理解正确,您可以使用两个级别的聚合:

SELECT merchant_id, SUM(num_zips)
FROM (SELECT merchant_id, article_id, COUNT(DISTINCT zip_code) AS num_zips
      FROM main_table
      GROUP BY merchant_id, article_id
     ) ma
WHERE ma.num_zips > 1
GROUP BY merchant_id;

你知道我如何在邮政编码相同的情况下只包含重复项吗?我是否需要更改:“WHERE ma.num_zups=1”?@user12625679。如果这不起作用,你可能想问一个新问题。