如何仅返回特定列中的条目唯一的SQL表中的行?
例如,
假设我有桌子:
FRUIT COLOR
_____________
apple green
apple red
peach blue
banana red
我想编写一个PostgreSQL查询,它只返回FRUIT
列中的条目唯一的行,在这种情况下意味着返回最后2行。我怎么做?感谢。
答案 0 :(得分:1)
这是使用having
子句的基本练习。阅读文档:Aggregate Functions并比较这些查询:
select fruit, count(*)
from my_table
group by 1;
fruit | count
--------+-------
banana | 1
peach | 1
apple | 2
(3 rows)
select fruit
from my_table
group by 1
having count(*) = 1;
fruit
--------
banana
peach
(2 rows)
答案 1 :(得分:1)
如果你需要整排,
1)使用having
和join
:
select t.*
from
my_table as t join (
select fruit
from my_table
group by fruit
having count(*) = 1) as f on (t.fruit = f.fruit);
2)使用窗口功能:
select *
from (
select *, count(*) over (partition by fruit) as cnt
from my_table) as t
where
cnt = 1;
答案 2 :(得分:0)
特定列的典型SQL语法是
SELECT * FROM (
SELECT FRUIT, Count(FRUIT) AS NUM_OF_FRUITS FROM MyTable
GROUP BY City )
WHERE NUM_OF_FRUITS = 1
给出桃子和香蕉但是如果你想要整行,你可以使用下面的sql语法
SELECT * FROM MyTable
WHERE FRUIT IN (
SELECT * FROM (
SELECT FRUIT, Count(FRUIT) AS NUM_OF_FRUITS FROM MyTable
GROUP BY City )
WHERE NUM_OF_FRUITS = 1
)
我认为这对你的问题已经足够了。