组中的条件排序

时间:2018-02-07 08:32:21

标签: sql sql-server sorting group-by sql-server-2014

请考虑此结果集:

Name     Value1     Value2     Value3
---------------------------------------
ccc       1          2           3
aaa       3          4           3
bbb       2          8           5
Group 1   2          1           3
rrr       1          2           5
mmm       3          4           4
nnn       3          2           1
eee       2          6           5
Group 2   2          4           4
...

如您所见,每组中的记录不按字母顺序排序。我如何按字母顺序对每组中的记录进行排序?

所需的结果集是:

Name     Value1     Value2     Value3
---------------------------------------
aaa       3          4           3
bbb       2          8           5
ccc       1          2           3
Group 1   2          1           3
eee       2          6           5
mmm       3          4           4
nnn       3          2           1
rrr       1          2           5
Group 2   2          4           4
...

编辑1)

生成基础结果集的代码:

DECLARE @tbl AS Table
(
    Name NVARCHAR(50),
    Value1 DECIMAL(5,2),
    Value2 DECIMAL(5,2),
    Value3 DECIMAL(5,2)
)   

INSERT INTO @tbl VALUES('ccc',1,2,3)
INSERT INTO @tbl VALUES('aaa',3,4,3)
INSERT INTO @tbl VALUES('bbb',2,8,5)
INSERT INTO @tbl VALUES('Group 1',2,1,3)
INSERT INTO @tbl VALUES('rrr',1,2,5)
INSERT INTO @tbl VALUES('mmm',3,4,4)
INSERT INTO @tbl VALUES('nnn',3,2,1)
INSERT INTO @tbl VALUES('Group 2',2,4,4)

select * from @tbl

1 个答案:

答案 0 :(得分:5)

试试这个:

select * from (
    select Name, value1, value2, value3,
        case when Name like 'group%' then SUM(Groups) over (order by (select null) rows between unbounded preceding and current row) - 1
        else SUM(Groups) over (order by (select null) rows between unbounded preceding and current row) end [groupingCol],
        groups
    from (
        select *,
        case when Name like 'group%' then 1 else 0 end [Groups] from @tbl
     ) a
) b order by groupingCol, Groups, name