使用查询结果获取列中重复值的计数

时间:2013-01-01 12:10:41

标签: mysql

我想知道在查询结果的列中结果中重复的值有多少。

我从复杂查询得到的结果集是 -

svn rvn eng     count(*)
1   1   Boy            1
2   1   Teacher        1
3   1   Chair          1
3   2   Chairwoman      1
3   3   Chairperson     1
4   1   Without         1
4   2   Without fail    1
5   1   Anyone          1
5   2   Anyone else     1
6   1   Permission      1

我只想在第四列SVN coloumn中获取重复值的数量。

svn rvn eng     count(*)
1   1   Boy            1
2   1   Teacher        1

3   1   Chair          3
3   2   Chairwoman      3
3   3   Chairperson     3

4   1   Without         2
4   2   Without fail    2

5   1   Anyone          2
5   2   Anyone else     2
6   1   Permission      1

请帮我解决这个问题,请告诉我这会对查询效率产生什么影响?

* 注意 - * 我想要在结果集中选取的值的计数。 表格中有更多条目svn 1,2,4,6。但只计算已选择的数量。

提前致谢:)

EDIT1

这是我当前的查询: -

SELECT `svn` , `rvn` ,`eng` , count(*) FROM 
        (SELECT `svn`, `rvn`, `eng`, `hin` 
              FROM `table1` 
              WHERE `SN` = @sn
            UNION DISTINCT
            SELECT `table1_refer`.`sn_svn` AS 'svn',  
                           `table1`.`rvn`, `table1`.`eng` ,  
                          `vocab_rel`.`hin`
            FROM  `table1` 
            JOIN  `table1_refer` 
            WHERE  `table1_refer`.`rSN` =  `table1`.`SN` 
            AND  `table1_refer`.`svn` =  `table1`.`svn` 
            AND `table1_refer`.`SN` = @sn
        ) AS SUBQUERY
        GROUP BY `svn`,`rvn`
        ORDER BY `svn`, `rvn`

1 个答案:

答案 0 :(得分:6)

您可以在当前复杂查询中使用相关子查询来执行此操作:

SELECT
  svn, 
  rvn,
  eng,
  (SELECT count(t2.svn)
   FROM Tablename t2
   WHERE t2.svn = t1.svn
  ) AS Count
FROM Tablename t1
....

SQL Fiddle Demo

这会给你:

| SVN | RVN |         ENG | COUNT |
-----------------------------------
|   1 |   1 |         Boy |     1 |
|   2 |   1 |     Teacher |     1 |
|   3 |   1 |       Chair |     3 |
|   3 |   2 |  Chairwoman |     3 |
|   3 |   3 | Chairperson |     3 |
|   4 |   1 |     Without |     2 |
|   4 |   2 | Withoutfail |     2 |
|   5 |   1 |      Anyone |     2 |
|   5 |   2 |  Anyoneelse |     2 |
|   6 |   1 |  Permission |     1 |