我想知道我的哪些用户在他们的机器上有一个独特的操作系统
我对任何不完全独特的人都不感兴趣。 (我们在这里寻找孤独的狼)我不是在寻找独特的价值观。只是完全独特的记录。
这是SQL
CREATE TABLE `Computers` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`CPU` VARCHAR(45) NULL ,
`OS` VARCHAR(45) NULL ,
PRIMARY KEY (`ID`) );
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('386', 'win 3.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('486', 'Dr Doss');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('286', 'win 3.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('68000', 'Mac OS 7.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('68030', 'Mac OS 7.1');
INSERT INTO `Computers` (`CPU`, `OS`) VALUES ('Z80', 'CPM');
鉴于此数据,我应该只返回以下行:
ID OS
2 Dr Doss
6 CPM
有人可以帮我解决SQL语句吗?
答案 0 :(得分:3)
将GROUP BY
子句与HAVING COUNT()
一起使用。
SELECT ID, OS
FROM Computers
GROUP BY OS
HAVING COUNT(OS) = 1;
GROUP BY
子句将其缩小为每个操作系统一行,HAVING
子句筛选出表中有多行的操作系统。
答案 1 :(得分:1)
http://sqlfiddle.com/#!2/cbfc2/11
使用上面提供的示例
select min(`id`), `os`, count(*) as total
from computers
group by `os`
having `total` = 1
答案 2 :(得分:0)
答案 3 :(得分:0)
SELECT *
FROM computers
INNER JOIN
(
SELECT OS, COUNT(*) AS OsCount
FROM computers
GROUP BY OS
HAVING OsCount = 1
) Sub1
ON computers.OS = Sub1.OS