我目前有一个带有两列OriginalName和SocialName的表 我正在尝试使用order by来按这两个顺序进行排序,但是问题是我希望在order by上考虑这两列,但是我的结果是按第一列排序,然后按另一列排序。
我的桌子上有这样的值
v1 | [1, 2, 3]
v2 | [4, 5]
v3 | [1, 7]
订购后,结果如下所示
[v1, v3] | [1, 2, 3, 7]
[v2] | [4, 5]
如您所见,它确实是在对表进行排序,但是它是在对社会名称进行排序,然后对原始名称进行排序,例如,OriginalName Cris colaboradora不应该在社会名称DannyTargarião之后,我真正想要的是考虑两列像这样:
OriginalName SocialName
Beatriz N G LEMES BEA LEMES
Carol Susan Jane Danvers Carol Danvers
Cris colaboradora Nome Social Cris
Lucas André Márcio Rodrigues NULL
Vinicius Cláudio Miguel Aragão Alice Castro
Miguel Carlos Eduardo Farias Alessandra Farias
Isis Aparecida Cristiane Assis Isis Assis
Danéria Targarião Danny Targarião
select OriginalName,SocialName
order by case when Coalesce(SocialName,'') = '' then 1 else 0 end , pfi.NomeSocial, pfi.Nome desc
答案 0 :(得分:1)
在ORDER BY子句中使用2个case语句:
select * from tablename
order by
case when Coalesce(SocialName,'') = '' then 1 else 0 end,
case
when OriginalName < SocialName then OriginalName
else SocialName
end
请参见demo。
结果:
> OriginalName | SocialName
> :------------------------------- | :----------------
> Miguel Carlos Eduardo Farias | Alessandra Farias
> Vinicius Cláudio Miguel Aragão | Alice Castro
> Beatriz N G LEMES | BEA LEMES
> Carol Susan Jane Danvers | Carol Danvers
> Cris colaboradora | Nome Social Cris
> Danéria Targarião | Danny Targarião
> Isis Aparecida Cristiane Assis | Isis Assis
> Lucas André Márcio Rodrigues | null
答案 1 :(得分:0)
您可以检查以下脚本吗?该脚本可以提供您期望的输出。
在这里检查Demo。
SELECT
SUBSTRING(Combined,1,CHARINDEX('###',Combined,1)-1) OriginalName,
SUBSTRING(Combined,CHARINDEX('###',Combined,1)+3,LEN(Combined)) SocialName,
MIN(RN)
FROM
(
SELECT Combined,ROW_NUMBER() OVER(ORDER BY OriginalName) RN
FROM
(
SELECT OriginalName,OriginalName+'###'+SocialName Combined FROM your_table
UNION ALL
SELECT SocialName,OriginalName+'###'+SocialName FROM your_table
)A
)B
GROUP BY SUBSTRING(Combined,1,CHARINDEX('###',Combined,1)-1),
SUBSTRING(Combined,CHARINDEX('###',Combined,1)+3,LEN(Combined))
ORDER BY 3