【问题标题】:How to retrieve same column twice from one table with Where condition如何使用 Where 条件从一个表中检索同一列两次
【发布时间】:2012-11-28 06:07:47
【问题描述】:

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

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

帮帮我..谢谢

【问题讨论】:

  • 我真的不喜欢“紧急”的请求。
  • 您尚未解释您的逻辑或显示查询所需的所有数据:您在查询中引用的 Place 列是什么?
  • 请用一些示例数据设置sqlfiddle
  • 需要提供基础表的样本数据,结果不够。
  • 你想用你的预期输出建立什么样的关系?现在对我来说,它似乎是随机的。

标签: sql sql-server tsql pivot


【解决方案1】:

您应该可以使用类似这样的东西,其中包含 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 with Demo

或者您可以使用带有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 with Demo

两者产生相同的结果:

|       MALE |     FEMALE |
---------------------------
|    Cricket | BasketBall |
| BasketBall |     Tennis |
|     Hockey | Volly Ball |

【讨论】:

  • ahh Pivoting....非常感谢...我很着急所以不能正确发布问题...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多