I have a table that looks like this
id + kID -------------------------- 0 | 3 1 | 6 2 | 7 3 | 6 4 | 7 5 | 5
What I want to do is find the amount of rows where the kID
occurs only once. So in this case the value of the variable should be 2
because kID: 3 and 5 occurs only once
so i'm trying to count that while ignoring everything else. I am really stumped, thanks for any help.
This will show kID
s that occur only once:
SELECT kID, COUNT(kID)
FROM table
GROUP BY kID
HAVING COUNT(kID) < 2
Result
| KID | COUNT(KID) | -------------------- | 3 | 1 | | 5 | 1 |
Then to get the total count of those:
SELECT Count(*) AS count
FROM (SELECT kid,
Count(kid)
FROM tbl
GROUP BY kid
HAVING Count(kid) < 2) a
Result
| COUNT | --------- | 2 |
Try this
SELECT
id,
count(kID) as `Count`
FROM mytable as t
GROUP BY kID
HAVING Count = 1
How about
select count(*) from
(select kid, count(*) from table group by kid having count(*) = 1)
You could do the following:
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
You could do it with a sub-select. This should work, though might not be extremely efficient:
SELECT id, kID, COUNT(1) FROM (SELECT COUNT(1),kID FROM TABLE
GROUP BY kID
HAVING COUNT = 1)
One more way to do it. It will work as long as the (id)
is the primary key of the table or there is a unique constraint on (kid, id)
:
SELECT COUNT(*) AS cnt
FROM
( SELECT NULL
FROM tableX
GROUP BY kid
HAVING MIN(id) = MAX(id)
) AS g ;
Tested at SQL-Fiddle
An index on (kid, id)
will improve efficiency - and only one COUNT()
will be done, not 2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.