计算MySQL列中的唯一数字

时间:2012-10-23 13:37:05

标签: mysql sql

我有一个以下列格式返回数据的查询:

id | name | number
 1   John    12545
 1   John    50496
 2   Mary    23443
 3   Mark    54
 3   Mark    5600
 3   Mark    50206

我想找出结果集中出现的不同ids的数量。例如,对于上面的结果。我想获得值3。

有没有办法添加一列,所以结果看起来像这样呢?

count | id | name | number
 3      1   John    12545
 3      1   John    50496
 3      2   Mary    23443
 3      3   Mark    54
 3      3   Mark    5600
 3      3   Mark    50206

我的查询是:

 SELECT * FROM (
    SELECT id FROM tableA
    WHERE xyz
 ) as t1
 JOIN tableB using (id)

4 个答案:

答案 0 :(得分:4)

SELECT (SELECT COUNT(DISTINCT id) FROM tableName) totalCount,
       id,name,number
FROM tableName

或使用CROSS JOIN

SELECT x.totalCount,
       a.id, a.name, a.number
FROM tableName a, (SELECT COUNT(DISTINCT id) totalCount 
                   FROM tableName) x

答案 1 :(得分:0)

你应该尝试:

SELECT id,name,number, (SELECT COUNT(DISTINCT name) FROM YourTableName) FROM YourTableName

祝你好运

答案 2 :(得分:0)

SELECT COUNT(DISTINCT id)比使用列name更快。

SELECT (SELECT COUNT(DISTINCT id) FROM tableName) as 'count',
        id,name,number  
FROM tableName

答案 3 :(得分:0)

SELECT COUNT(id) AS count , id, name, number 
FROM 
( 
    SELECT id 
    FROM tableA 
    WHERE xyz 
) as t1 
JOIN tableB using (id)
GROUP BY id, name, number