以替代方式对数据进行排序

时间:2019-08-01 10:30:31

标签: sql

我有下表

EID Ename   Gender
1   A   M
2   B   M
3   C   F
4   D   M
5   E   F
6   F   F
7   G   F
8   H   M

需要像下面这样排序

EID Ename   Gender
1   A   M
3   C   F
2   B   M
5   E   F
4   D   M
6   F   F
8   H   M
7   G   F

4 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER的一个选项:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Gender ORDER BY EID) rn
    FROM yourTable
)

SELECT
    EID, Ename, Gender
FROM cte
ORDER BY
    rn,
    CASE WHEN Gender = 'M' THEN 0 ELSE 1 END;

请注意,我们可能需要两个 排序级别,以确保男性条目出现在女性条目之前(尽管按年显示的特定数据并非必需)。

答案 1 :(得分:1)

尝试一下。

  ; with cte as (
   select row_number() over (partition by gender order by Eid) as Slno, * from table)
   select EID, Ename,   Gender from cte order by slno

答案 2 :(得分:0)

没有窗口功能,它将在任何rdbms中工作:

select t.eid, t.ename, t.gender
from tablename t  
order by 
  (select count(*) from tablename where gender = t.gender and eid < t.eid), 
  t.gender desc

请参见demo
结果:

> eid | ename | gender
> --: | :---- | :-----
>   1 | A     | M     
>   3 | C     | F     
>   2 | B     | M     
>   5 | E     | F     
>   4 | D     | M     
>   6 | F     | F     
>   8 | H     | M     
>   7 | G     | F     

答案 3 :(得分:0)

您可以直接在order by中使用窗口功能:

select t.*
from t
order by row_number() over (partition by gender order by eid),
         gender desc,
         eid;