2016-08-03 54 views
0

我不确定是否可以在SQL本身中只使用一个查询来完成它,但这就是我要问的原因。选择出现次数最少的列值

有没有办法让表中最少出现列值?

的表看起来像:

| Id | Value | 
-------------- 
| 1 | Banana| 
| 2 | Carrot| 
| 3 | Apple | 
| 4 | Apple | 
| 5 | Banana| 
| 6 | Apple | 
| 7 | Apple | 
| 8 | Banana| 
| 9 | Apple | 

现在有一个“胡萝卜”的值用最少的出现,如何将一个SQL模样让用最少出现的价值?有点令人困惑,也许你会第一次尝试不明白。谢谢。

回答

0

下面是一个方法:

select value 
from t 
group by value 
order by count(*) 
fetch first 1 row only; 

fetch first 1 row only是ANSI标准的语法,由几个数据库的支持。有些拼写为limitselect top 1

+0

请试试看。谢谢 –

1

让我们重新创建测试用例:

sqlite> create table vegetables(id int, value text); 
sqlite> insert into vegetables values('1', 'Banana'); 
sqlite> insert into vegetables values('2', 'Carrot'); 
sqlite> insert into vegetables values('3', 'Apple'); 
sqlite> insert into vegetables values('4', 'Apple'); 
sqlite> insert into vegetables values('5', 'Banana'); 
sqlite> insert into vegetables values('6', 'Apple'); 
sqlite> insert into vegetables values('7', 'Apple'); 
sqlite> insert into vegetables values('8', 'Banana'); 
sqlite> insert into vegetables values('9', 'Apple'); 

检查的数据是一样的你:

sqlite> select * from vegetables; 
1|Banana 
2|Carrot 
3|Apple 
4|Apple 
5|Banana 
6|Apple 
7|Apple 
8|Banana 
9|Apple 

如果你想用最少的出现蔬菜:

sqlite> select value from vegetables group by value order by count(value) limit 1; 
Carrot 

如果你想要的蔬菜出现次数最多:

sqlite> select value from vegetables group by value order by count(value) desc limit 1; 
Apple