我有一张看起来像这样的表
id + kID -------------------------- 0 | 3 1 | 6 2 | 7 3 | 6 4 | 7 5 | 5
我想要做的是找到kID
仅出现一次的行数。所以在这种情况下,变量的值应该是2
,因为kID: 3 and 5 occurs only once
所以我试图计算它而忽略其他所有内容。我真的很难过,谢谢你的帮助。
答案 0 :(得分:4)
这将显示仅出现一次的kID
:
SELECT kID, COUNT(kID)
FROM table
GROUP BY kID
HAVING COUNT(kID) < 2
<强>结果强>
| KID | COUNT(KID) | -------------------- | 3 | 1 | | 5 | 1 |
然后得到那些的总数:
SELECT Count(*) AS count
FROM (SELECT kid,
Count(kid)
FROM tbl
GROUP BY kid
HAVING Count(kid) < 2) a
<强>结果强>
| COUNT | --------- | 2 |
答案 1 :(得分:0)
试试这个
SELECT
id,
count(kID) as `Count`
FROM mytable as t
GROUP BY kID
HAVING Count = 1
答案 2 :(得分:0)
怎么样
select count(*) from
(select kid, count(*) from table group by kid having count(*) = 1)
答案 3 :(得分:0)
您可以执行以下操作:
select count(*) from
(
select kID, COUNT(*) [c] from tableName
group by kID
) t
where t.c = 1
答案 4 :(得分:0)
SELECT kID,
COUNT(kID)
FROM tableName
GROUP BY kID
HAVING COUNT(kID) = 1
答案 5 :(得分:0)
您可以通过子选择来完成。这应该有效,但可能效率不高:
SELECT id, kID, COUNT(1) FROM (SELECT COUNT(1),kID FROM TABLE
GROUP BY kID
HAVING COUNT = 1)
答案 6 :(得分:0)
另一种方法。只要(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. {/ p>