Bạn đang gặp phải một vấn đề về chữ hoa:Tên của bạn đều được viết hoa, nhưng các email là chữ thường và với hầu hết các ảnh ghép, chữ hoa đứng trước chữ thường. Hãy xem ví dụ nhỏ này:
#= select * from (values ('b'), ('B'), ('a'), ('A')) t (letter);
letter
--------
b
B
a
A
#= select * from (values ('b'), ('B'), ('a'), ('A')) t (letter) order by letter;
letter
--------
A
B
a
b
Vì vậy, truy vấn của bạn thực sự hoạt động hoàn hảo, chỉ là example@sqldat.com sắp xếp sau Josh . Để tránh điều này, bạn có thể sắp xếp theo giá trị chữ thường. Đây là phiên bản đơn giản của dữ liệu bạn có:
#= select * from volunteers;
first_name | last_name | email
------------+-----------+--------------------
Josh | Broger | example@sqldat.com
Josh | Kenton | example@sqldat.com
∅ | ∅ | example@sqldat.com
Josh | Broger | example@sqldat.com
Alex | Diego | example@sqldat.com
Sau đó, để sắp xếp bằng cách sử dụng coalesce bạn đang theo đuổi:
#= select * from volunteers order by lower(coalesce(first_name, email));
first_name | last_name | email
------------+-----------+--------------------
Alex | Diego | example@sqldat.com
∅ | ∅ | example@sqldat.com
Josh | Broger | example@sqldat.com
Josh | Broger | example@sqldat.com
Josh | Kenton | example@sqldat.com
Hoặc đối với phiên bản đầy đủ của bạn bằng cách sử dụng ActiveRecord :
Volunteer
.joins(:volunteer_lists)
.where(
"(volunteer_lists.organizer_id = ? AND organizer_type = 'Organization') OR (volunteer_lists.organizer_id IN (?) AND organizer_type = 'Collaborative')",
organization.id, collaboratives
)
.order('LOWER(COALESCE("volunteers"."first_name", "volunteers"."last_name", "volunteers"."email"))')