SQL Table 中数据子集的 ORDER BY
SQL ORDER BY on Subset of Data in Table
我有一个 table 结构如下:
Table: Details
ID | ParentName | ChildName
1 | ParentA | ChildA
2 | ParentA | ChildC
3 | ParentA | ChildB
4 | ParentB | ChildL
5 | ParentB | ChildS
6 | ParentB | ChildT
7 | ParentB | ChildM
8 | ParentB | ChildP
9 | ParentB | ChildR
10 | ParentC | ChildZ
仅当 ParentName 为 ParentB 时,我才需要按升序对 ChildName 进行排序,对于其他 ParentName - 不应应用排序
所以基本上我只需要对数据的子集进行排序,即。当ParentName = ParentB,其他数据保持原样。
我尝试了以下查询,但它正在对所有记录进行排序 - 但我只需要为 ParentB 排序
SELECT * FROM DETAILS WITH (NOLOCK) ORDER BY ParentName , ChildName
预期结果是:只对ParentName = ParentB进行排序,其他数据相同
ID | ParentName | ChildName
1 | ParentA | ChildA
2 | ParentA | ChildC
3 | ParentA | ChildB
4 | ParentB | ChildL
7 | ParentB | ChildM
8 | ParentB | ChildP
9 | ParentB | ChildR
5 | ParentB | ChildS
6 | ParentB | ChildT
10 | ParentC | ChildZ
如有任何帮助或建议,我们将不胜感激。
提前致谢
您可以在 ORDER BY
子句中使用 CASE
表达式
order by ParentName,
case when ParentName = 'ParentB' then ChildName end,
ID
我有一个 table 结构如下:
Table: Details
ID | ParentName | ChildName
1 | ParentA | ChildA
2 | ParentA | ChildC
3 | ParentA | ChildB
4 | ParentB | ChildL
5 | ParentB | ChildS
6 | ParentB | ChildT
7 | ParentB | ChildM
8 | ParentB | ChildP
9 | ParentB | ChildR
10 | ParentC | ChildZ
仅当 ParentName 为 ParentB 时,我才需要按升序对 ChildName 进行排序,对于其他 ParentName - 不应应用排序 所以基本上我只需要对数据的子集进行排序,即。当ParentName = ParentB,其他数据保持原样。
我尝试了以下查询,但它正在对所有记录进行排序 - 但我只需要为 ParentB 排序
SELECT * FROM DETAILS WITH (NOLOCK) ORDER BY ParentName , ChildName
预期结果是:只对ParentName = ParentB进行排序,其他数据相同
ID | ParentName | ChildName
1 | ParentA | ChildA
2 | ParentA | ChildC
3 | ParentA | ChildB
4 | ParentB | ChildL
7 | ParentB | ChildM
8 | ParentB | ChildP
9 | ParentB | ChildR
5 | ParentB | ChildS
6 | ParentB | ChildT
10 | ParentC | ChildZ
如有任何帮助或建议,我们将不胜感激。
提前致谢
您可以在 ORDER BY
子句中使用 CASE
表达式
order by ParentName,
case when ParentName = 'ParentB' then ChildName end,
ID