0

I'm getting data like this

  • Doha
  • doha
  • Dubai
  • Abu Dhabi
  • Abu dhabi

from the query select distinct(trim(name)) as loc from locations order by trim(name)

Now I want to remove duplicates using lower() or upper() and select the first record . If I use lower function like below,

select distinct(lower(A.loc)) from( select distinct(trim(name)) as loc from locations order by trim(name) ) as A order by lower(A.loc);

it gives result converted to lower as below.

  • doha

  • dubai

  • abu dhabi

    But I want original result as previously mentioned.

  • Doha

  • Dubai

  • Abu Dhabi

4

1 回答 1

1

演示:db<>小提琴

SELECT DISTINCT ON (lower(city))
    city
FROM
    cities

DISTINCT ON取任意列并给出第一个重复项。在这种情况下,会在内部创建一个全部小写的列。然后取第一条记录,但只取原始列。


注意您没有特殊订单。它将采用随机顺序(例如数据在内部存储的方式)。要实现大写值,您必须编写:

SELECT DISTINCT ON (lower(city))
    city
FROM
    cities
ORDER BY lower(city), city DESC

演示:db<>小提琴

ORDER BY lower(city)是必要的,因为DISTINCT ON需要给定的列是第一个排序的。之后,您可以按任何其他列订购。ORDER BY column DESC将大写字母移到顶部。

于 2019-05-07T13:31:11.507 回答