如何在SQL Server中替代男性和女性

时间:2019-03-23 11:42:48

标签: sql-server sql-server-2012

我对SQL Server有一个疑问:如何获取公母数据的替代数据

CREATE TABLE [dbo].[EmpGenders]
(
    [id] [INT] NULL,
    [Name] [VARCHAR](50) NULL,
    [Gender] [VARCHAR](50) NULL
) 

INSERT INTO [dbo].[EmpGenders] ([id], [Name], [Gender]) 
VALUES (1, N'Manish', N'Male'), (2, N'Nayak', N'Male'),
       (3, N'Martin', N'Male'), (4, N'Roy', N'Male'),
       (5, N'Hardik', N'Male'), (6, N'Manisha', N'Female'),
       (7, N'Kruti', N'Female'), (8, N'Maria', N'Female')

基于以上数据,我想要这样的输出:

Id | Name    | Gender 
---+---------+---------
1  | Manish  | Male
6  | Manisha | Female
2  | Nayak   | Male
7  | Kruti   | Female
3  | Martin  | Male
8  | Maria   | Female
4  | Roy     | Male
5  | Hardik  | Male 

我尝试了以下SQL语句:

select 
    id, name, gender  
from 
    (select 
         *,
         row_number() over (order by id, gender) as rn
     from  
         [Test].[dbo].[EmpGenders]) a
where  
    rn % 2 = 1 

union all

select 
    id, name, gender  
from 
    (select 
         *, row_number() over (order by id desc, gender desc) as rn
     from  
         [Test].[dbo].[EmpGenders]) a  
where  
    rn % 2 = 0

但该查询未返回预期结果。

能否请您告诉我如何编写查询以在SQL Server中完成此任务?

2 个答案:

答案 0 :(得分:5)

你能不能做...

SELECT *
FROM EmpGenders
ORDER BY ROW_NUMBER() OVER(PARTITION BY Gender ORDER BY Id),
         Gender DESC;

答案 1 :(得分:1)

为每个子查询再增加1列,例如每种性别的num = 0 or 1

select id, name, gender from (
  select * ,row_number()over ( order by id )as rn, 0 as num
  from  [EmpGenders]
  where gender = 'Male'
  union all
  select * ,ROW_NUMBER()over ( order by id )as rn, 1 as num
  from  [EmpGenders] 
  where gender = 'Female'
  ) t
order by t.rn, t.num

请参见demo
注意:
拉努的答案被删除(!!!)更好。...