根据列的特定值按数据排序

时间:2013-08-12 05:52:59

标签: sql sql-server sql-server-2008 tsql

我正在使用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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 fiddle demo