0

我有一张看起来像这样的桌子

身份证+孩子       
--------------------------
0 | 3
1 | 6
2 | 7
3 | 6
4 | 7
5 | 5

我想要做的是找到kID只发生一次的行数。所以在这种情况下,变量的值应该是2因为kID: 3 and 5 occurs only once所以我试图计算它而忽略其他所有内容。我真的很难过,谢谢你的帮助。

4

7 回答 7

4

这将显示kID只出现一次的 s:

SELECT kID, COUNT(kID)
FROM table
GROUP BY kID
HAVING COUNT(kID) < 2

结果

| 孩子 | 计数(儿童)|
--------------------
| 3 | 1 |
| 5 | 1 |

查看演示

然后得到这些的总数:

SELECT Count(*) AS count 
FROM   (SELECT kid, 
               Count(kid) 
        FROM   tbl 
        GROUP  BY kid 
        HAVING Count(kid) < 2) a

结果

| 计数 |
---------
| 2 |

查看演示

于 2013-03-04T18:25:13.993 回答
0

试试这个

SELECT
  id,
  count(kID) as `Count`
FROM mytable as t
GROUP BY kID
HAVING Count = 1
于 2013-03-04T18:25:21.203 回答
0

怎么样

select count(*) from 
(select kid, count(*) from table group by kid having count(*) = 1)
于 2013-03-04T18:25:25.707 回答
0

您可以执行以下操作:

select count(*) from 
(
    select kID, COUNT(*) [c] from tableName
    group by kID
) t
where t.c = 1
于 2013-03-04T18:26:31.807 回答
0
SELECT kID, 
COUNT(kID) 
FROM tableName
GROUP BY kID
HAVING COUNT(kID) = 1
于 2013-03-04T18:26:39.753 回答
0

您可以使用子选择来做到这一点。这应该有效,但可能不是非常有效:

SELECT id, kID, COUNT(1) FROM (SELECT COUNT(1),kID FROM TABLE
                               GROUP BY kID
                               HAVING COUNT = 1)
于 2013-03-04T18:28:46.283 回答
0

另一种方法来做到这一点。只要(id)是表的主键或存在唯一约束,它就可以工作(kid, id)

SELECT COUNT(*) AS cnt
FROM
  ( SELECT NULL
    FROM tableX
    GROUP BY kid
    HAVING MIN(id) = MAX(id) 
  ) AS g ;

SQL-Fiddle测试

一个索引(kid, id)将提高效率 - 只会COUNT()做一个,而不是 2。

于 2013-03-04T18:39:13.443 回答