我想获得每个article_id
的merchant_id
的重复数量,其中zip_code
不相同。请参见下面的示例:
表格
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;