我有一张看起来像这样的桌子
身份证+孩子 -------------------------- 0 | 3 1 | 6 2 | 7 3 | 6 4 | 7 5 | 5
我想要做的是找到kID
只发生一次的行数。所以在这种情况下,变量的值应该是2
因为kID: 3 and 5 occurs only once
所以我试图计算它而忽略其他所有内容。我真的很难过,谢谢你的帮助。
这将显示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 |
试试这个
SELECT
id,
count(kID) as `Count`
FROM mytable as t
GROUP BY kID
HAVING Count = 1
怎么样
select count(*) from
(select kid, count(*) from table group by kid having count(*) = 1)
您可以执行以下操作:
select count(*) from
(
select kID, COUNT(*) [c] from tableName
group by kID
) t
where t.c = 1
SELECT kID,
COUNT(kID)
FROM tableName
GROUP BY kID
HAVING COUNT(kID) = 1
您可以使用子选择来做到这一点。这应该有效,但可能不是非常有效:
SELECT id, kID, COUNT(1) FROM (SELECT COUNT(1),kID FROM TABLE
GROUP BY kID
HAVING COUNT = 1)
另一种方法来做到这一点。只要(id)
是表的主键或存在唯一约束,它就可以工作(kid, id)
:
SELECT COUNT(*) AS cnt
FROM
( SELECT NULL
FROM tableX
GROUP BY kid
HAVING MIN(id) = MAX(id)
) AS g ;
一个索引(kid, id)
将提高效率 - 只会COUNT()
做一个,而不是 2。