简体   繁体   English

PostgreSQL GROUP BY LOWER()无效

[英]PostgreSQL GROUP BY LOWER() not working

I am trying to use GROUP BY in PostgreSQL 9.4.1 and not having as much success as I hoped. 我试图在PostgreSQL 9.4.1中使用GROUP BY而没有像我希望的那样成功。

There are several folks on the web that claim this should work, but I can't get the same results. 网上几个人声称这应该有效,但我无法得到相同的结果。 All I want is a case-insensitive GROUP BY but every time I add LOWER() it complains with: 我想要的只是一个不区分大小写的GROUP BY但每次添加LOWER()都会抱怨:

ERROR: column "people.fn" must appear in the GROUP BY clause or be used in an aggregate function 错误:列“people.fn”必须出现在GROUP BY子句中或用于聚合函数

CREATE DATABASE TEST;
CREATE TABLE people (id INTEGER, fn TEXT, ln TEXT); /* ID, firstname, lastname */

INSERT INTO people (id, fn, ln) VALUES(1,'Mike','f');
INSERT INTO people (id, fn, ln) VALUES(2,'adam','b');
INSERT INTO people (id, fn, ln) VALUES(3,'bill','b');
INSERT INTO people (id, fn, ln) VALUES(4,'Bill','r');
INSERT INTO people (id, fn, ln) VALUES(5,'mike','d');
INSERT INTO people (id, fn, ln) VALUES(6,'mike','c');
INSERT INTO people (id, fn, ln) VALUES(7,'Mike','T');

SELECT fn FROM people GROUP BY LOWER(fn);  /* will not run */
SELECT fn FROM people GROUP BY fn;  /* runs, but not what I want */

Here's what I get: 这是我得到的:

adam
mike
Mike
bill
Bill

Here's what I want: 这就是我想要的:

Mike
adam
bill

Obviously, there's something I'm missing. 显然,我缺少一些东西。 And no, I can't just sanitize the data as I put it into the database. 不,我不能在将数据放入数据库时​​清理数据。 What should I read to understand this? 我应该阅读什么来理解这一点?

Generally, if you want to select something in the aggregate query, you have to group by this "something". 通常,如果要在聚合查询中选择某些内容,则必须按此“分组”进行分组。 In your case, you can get results you want by selecting lower(fn) : 在您的情况下,您可以通过选择lower(fn)来获得所需的结果:

select lower(fn)
from people
group by lower(fn)

Luckily, PostgreSQL allows you to group by alias, so you don't have to repeat lower(fn) twice: 幸运的是,PostgreSQL允许您按别名分组,因此您不必重复lower(fn)两次:

select lower(fn) as lfn
from people
group by lfn

sql fiddle demo sql小提琴演示

As @okaram mentioned in the comments, if you don't need any other aggrgation on the table, you'd better use distinct : 正如@okaram在评论中提到的,如果你不需要在桌子上进行任何其他的侵害,你最好使用distinct

select distinct lower(fn)
from people

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM