假设我有一张看起来像这样的表,或者我可能无处可去。
create table customers (id text, name text, number int, useless text);
带值
insert into customers (id, name, number, useless)
values
('1','apple',1, 'a'),
('2','banana',3, 'b'),
('3','pear',2, 's'),
('4','apple',1,'e'),
('5','banana',3,'s'),
('6','cherry',3, 'a'),
('7','cherry',4, 's'),
('8','apple',2, 'd'),
('9','banana',4, 'c'),
('10','pear',5, 'e');
我失败的psql查询是这样的。
select id, name, number, useless
from customers
where number < 4
group by customers.name limit 2
我想要使用的查询,它返回由customers.name分组的前2个唯一。不是前两行
最后我希望它返回
('1','apple',1, 'a'),
('4','apple',1,'e'),
('8','apple',2, 'd'),
('2','banana',3, 'b'),
('5','banana',3,'s'),
所以它返回前2个分组名称。 我该如何进行此查询?
谢谢。
编辑:
这个查询是我的第二次尝试,我知道我有点亲近。
select t.id, t.name, t.ranking
from (
SELECT id, name, dense_rank() OVER (order by name) as
ranking
FROM customers
group by name
) t
where t.ranking < 3
答案 0 :(得分:2)
试试这个:
select id, name, number, useless
from customers
where name in (
select name
from customers
where number < 4
group by customers.name
order by name limit 2
)
| id | name | number | useless |
|----|--------|--------|---------|
| 1 | apple | 1 | a |
| 2 | banana | 3 | b |
| 4 | apple | 1 | e |
| 5 | banana | 3 | s |
| 8 | apple | 2 | d |
| 9 | banana | 4 | c |
答案 1 :(得分:0)
group by customers.name
函数不对您的输出进行排序,只需按customers.name对它们进行分组,您要做的是对该组进行排序吗?所以我认为你想做的是:
select id, name, number, useless
from customers
group by name
order by name []*
* [asc / desc]取决于您想要的顺序:
希望它对你有所帮助。
答案 2 :(得分:0)
您可以将dense_rank()
用作:
SELECT * FROM (
SELECT DENSE_RANK() OVER (order by name) AS rank, temp.*
FROM customers temp WHERE number < 4) data
WHERE data.rank <= 2
| rank| id| name | number | useless |
|-----|---|--------|--------|---------|
| 1 | 4 | apple | 1 | e |
| 1 | 1 | apple | 1 | a |
| 1 | 8 | apple | 2 | d |
| 2 | 5 | banana | 3 | s |
| 2 | 2 | banana | 3 | b |