-2

我试图从一个表中检索一列两次,例如:

select M.Event_Name as 'Male',
       F.Event_Name as 'Female' 
from   Table1 M, Table1 F
where  M.Gender = 'M'
       and F.Gender = 'F'
       and F.Country = 12
       and M.Country = 12

表1数据

ID    Event_Name   Gender  Country
1     Cricket      M       12
2     FootBall     M       13
3     BasketBall   M       12
4     Hockey       M       12
5     Tennis       M       13
6     Volly Ball   M       13
7     Cricket      F       13
8     FootBall     F       13
9     BasketBall   F       12
10    Hockey       F       13
11    Tennis       F       12
12    Volly Ball   F       12

我得到的是:

Male           Female
Cricket        Tennis
Cricket        BasketBall
Cricket        Volly ball
BasketBall     Tennis
BasketBall     BasketBall
BasketBall     Volly ball
Hockey         Tennis
Hockey         BasketBall
Hockey         Volly ball

期待:

Male          Female
Cricket       Tennis
BasketBall    BasketBall
Hockey        Volly ball

帮帮我。。谢谢

4

1 回答 1

0

您应该能够使用这样的东西,其中包含PIVOT

select M as Male, 
  F as Female
from
(
  select event_name, gender,
    row_number() over(partition by gender, country order by id) rn
  from yourtable
  where gender in ('M', 'F')
    and country = 12
) src
pivot
(
  max(event_name)
  for gender in (M, F)
) piv

请参阅带有演示的 SQL Fiddle

或者您可以使用带有CASE语句的聚合函数:

select 
  max(case when gender = 'M' then event_name end) male,
  max(case when gender = 'F' then event_name end) female
from
(
  select event_name, gender,
      row_number() over(partition by gender, country order by id) rn
  from yourtable 
  where gender in ('M', 'F')
    and country = 12
) src
group by rn

请参阅带有演示的 SQL Fiddle

两者都产生相同的结果:

|       MALE |     FEMALE |
---------------------------
|    Cricket | BasketBall |
| BasketBall |     Tennis |
|     Hockey | Volly Ball |
于 2012-12-10T19:39:50.223 回答