SQL - 如果值存在则按列排序,否则为第二列

时间:2014-06-11 09:22:32

标签: sql postgresql sql-order-by multiple-columns

如何按列name排序SQL结果,如果没有设置名称,请按email排序。

+----+-------+-----------------+
| ID | name  |      email      |
+----+-------+-----------------+
|  1 | John  | john@gmail.com  |
|  2 | ---   | linda@gmail.com |
|  3 | ---   | kikli@gmail.com |
|  4 | Peter | peter@gmail.com |
+----+-------+-----------------+

结果应如下所示:

John, kikli@gmail.com, linda@gmail.com, Peter

答案:

$users = $this->em->createQueryBuilder()
        ->select('a.id, coalesce(concat(a.firstName, concat(\' \', a.lastName)), a.email) as orderColumn')
        ->from('Company\User\Admin', 'a')
        ->orderBy('orderColumn','ASC')
        ->getQuery()
        ->getScalarResult();

4 个答案:

答案 0 :(得分:2)

什么意思是“没有设置名称”?是NULL还是'---'?但是,您可以使用CASE

SELECT 
    CASE WHEN Name IS NULL THEN Email ELSE Name END AS User
FROM 
    dbo.TableName
ORDER BY
    CASE WHEN Name IS NULL THEN Email ELSE Name END ASC, Email ASC

答案 1 :(得分:1)

试试这个

SELECT MyName = CASE 
        WHEN NAME = '---'
            THEN Email
        ELSE NAME
        END
FROM YourTable
ORDER BY CASE 
        WHEN NAME = '---'
            THEN Email
        ELSE NAME
        END ASC

答案 2 :(得分:1)

select coalesce(lastName || ' ' || firstName, email)
from t
order by 1

1子句中的order by表示选择列表中的第一列。

当coalesce函数为

时,case表达式不可索引
create index t_index on t (coalesce(lastName || ' ' || firstName, email));

答案 3 :(得分:0)

简单快捷:

select name as output from tablename where name is not null
union
select email as output from tablename where name is null
order by output asc