2016-10-24 84 views
1

我有一张包含shop_id,名称和promotion_code的表格。我想获得每个shop_id的记录数量,但是有一些重复的记录,其中多次使用了promotion_code。我想忽略这些。忽略GROUP BY上的重复项

我曾尝试:

SELECT shop_id, count(*) as total_entries FROM tbl GROUP BY shop_id

这给了我正确的结构,但它确实指望所有的重复行。所以,我想我会尝试先对它们进行分组对PROMOTION_CODE,然后在shop_id:

SELECT shop_id, count(*) as total_entries FROM tbl GROUP BY promotion_code, shop_id

但是这给了我全零作为结果。

+0

添加一些样本表数据和预期的结果。 (以及格式化文本。) – jarlh

+0

顺便说一句,不可能为已发布的选择返回零。 – dnoeth

回答

2
SELECT shop_id, count(distinct promotion_code) as total_entries FROM tbl GROUP BY shop_id 
2

尝试:

select shop_id, count(distinct promotion_code) 
from tbl 
group by shop_id 
1

SELECT shop_id,COUNT(*)作为total_entries FROM TBL GROUP BY PROMOTION_CODE,shop_id

而不是使用(*),你可以使用DISTINCT函数,以确保您尝试分组的所有数据都是唯一值。

你可以做这样的事情:

SELECT shop_id, COUNT(DISTINCT promotion_code) as total_entries FROM tbl GROUP BY shop_id