如何按列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();
答案 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