按顺序计数

时间:2013-09-06 22:32:47

标签: mysql sql count distinct

我有一个包含id列表的数据集,这些id是一个类别列表(因此每个id可能有很多类别)。我想搜索一个类别列表,看看该类别中有多少不同的id(计数),但是一旦id计入一个类别,就不会计入另一个类别。

示例:

ID  Category
1    Gas Station
1    Convenience Store
1    Barber
2    Day Care
2    Gas station
3    Convenience Store
3    Golf Range

因此,如果我正在搜索加油站和便利店(按此顺序)的数量,Gas Station将获得2(对于id 1和2),然后便利店将获得1(id) 3)。

目前我的查询如下:

select category,distinct(id) from TABLE
where id in ('Gas Station','Convenience Store')
group by category 

它会给我

Gas Station - 2
Convenience Store - 2

这不是我想要的。期望的输出:

Gas Station - 2
Convenience Store - 1

2 个答案:

答案 0 :(得分:1)

为什么你想要这个输出并不是很清楚,但从技术上讲,你可以用查询来生成它

SELECT category, COUNT(DISTINCT id) count
  FROM table1
 WHERE category = 'Gas Station'
UNION ALL
SELECT category, COUNT(DISTINCT id) count
  FROM table1
 WHERE category = 'Convenience Store' 
   AND id NOT IN
       (
         SELECT DISTINCT id
           FROM table1
          WHERE category = 'Gas Station'
       );

输出:

|          CATEGORY | COUNT |
|-------------------|-------|
|       Gas Station |     2 |
| Convenience Store |     1 |

这是 SQLFiddle 演示

答案 1 :(得分:1)

<强>更新

尝试将其作为单个SQL:

SELECT Category
 ,COUNT(*)
 ,@ids:=CONCAT( @ids, ID, ',' )
 FROM Table1, (SELECT @ids:=',') ids
 WHERE Category IN ('Gas Station','Convenience Store')
 AND POSITION( CONCAT( ',', ID, ',' ) IN @ids ) = 0
 GROUP BY Category

http://sqlfiddle.com/#!2/2f026/12

上的SQLfiddle

<强>更新

确定。试试这个:

SET @ids:=',';
SELECT Category
      ,COUNT(*)
      ,@ids:=CONCAT( @ids, ID, ',' )
  FROM Table1
 WHERE Category IN ('Gas Station','Convenience Store')
   AND POSITION( CONCAT( ',', ID, ',' ) IN @ids ) = 0
 GROUP BY Category

修改@ peterm的sqlfiddle(http://sqlfiddle.com/#!2/2f026/1)结果为:

CATEGORY             COUNT(*)   @IDS:=CONCAT( @IDS, ID, ',' )
Convenience Store    1          ,1,3,
Gas Station          2          ,1,