-2

我正在使用 Sql server 2008,我需要按以下数据订购:

Id      PId     Name
1       1       A
1       2       G   --value to consider
1       3       C
2       1       A
2       2       B   --value to consider
2       3       C
3       1       A
3       2       D   --value to consider
3       3       C

结果应类似于:

Id      PId     Name
2       1       A
2       2       B
2       3       C
3       1       A
3       2       D
3       3       C
1       1       A
1       2       G
1       3       C

我按子句的顺序尝试了不同的组合,但没有用,例如:

order by Name, PId
order by PId, Name, Id
4

2 回答 2

2

您的问题不清楚您想要的顺序,但是如果您想按与 PId=2 的相同 Id 关联的名称订购,那么按 Pid,请尝试

select Id, PId, Name
from t
order by (
  select Name from t as t2
  where t2.Id = t.Id
  and t2.PId = 2
), PId
于 2013-08-12T05:58:32.110 回答
2
select T1.*
from Table1 as t1
    left outer join Table1 as T2 on T2.id = T1.id and T2.Pid = 2
order by T2.Name, T1.Pid

sql 小提琴演示

于 2013-08-12T05:59:41.310 回答