选择男性&女性的名字来自同一张桌子

时间:2012-10-23 05:49:10

标签: sql-server-2008

这是我的'联系人'表。

| Names      |   Gender   |

| Mike       | Male       |
| Steve      | Male       |
| Kelly      | Female     |
| Jane       | Female     |
| Natasha    | Female     |
| Mathew     | Male       |
| Jack       | Male       |

我想要那样的结果:

|  Male      |   Female   |   

| Mike       | Kelly      |
| Steve      | Jane       |
| Mathew     | Natasha    |
| Jack       |            |

请给我解决方案在SQL Sever中实现这个结果... 任何建议都表示赞赏!

1 个答案:

答案 0 :(得分:5)

with Male as
(
  select Names,
         row_number() over(order by Names) as rn
  from YourTable
  where Gender = 'Male'
),
Female as
(
  select Names,
         row_number() over(order by Names) as rn
  from YourTable
  where Gender = 'Female'
)
select Male.Names as Male,
       Female.Names as Female
from Male
  full outer join Female
    on Male.rn = Female.rn

SQL Fiddle

不是您想要的确切结果,但是如果没有其他列可以订购,那么它就会很好。

Male    Female
------- -------
Jack    Jane
Mathew  Kelly
Mike    Natasha
Steve   NULL