选择每个在SQL中具有特定where条件的列

时间:2014-07-14 18:07:35

标签: sql sql-server

我有一个表包含不同类的所有名称,如下所示:

Name   Class

Jack    A

Nick    B

Simon   C

David   B

Linda   B

Alice   C

现在我想获得一个以A,B,C为列的表,其中包含尊重类中的名称:

A----------B----------C

Jack------Nick-------Simon

----------David------Alice

----------Linda-----------

如何在SQL查询中获取此类表?抱歉格式不正确,不知道如何在SO中创建表格。

3 个答案:

答案 0 :(得分:3)

这是一种使用聚合的方法。这可能是最简单的方法:

select max(case when class = 'a' then name end) as a,
       max(case when class = 'b' then name end) as b,
       max(case when class = 'c' then name end) as c
from (select name, class, row_number() over (partition by class order by (select NULL)) as seqnum
      from nameclasses
     ) nc
group by seqnum
order by seqnum;

这是我发布的原始方法。它不使用聚合,但它做了很多连接:

select a.name as a, b.name as b, c.name as c
from (select name, row_number() over (order by (select NULL)) as seqnum
      from nameclasses nc
      where class = 'A'
     ) a full outer join
     (select name, row_number() over (order by (select NULL)) as seqnum
      from nameclasses nc
      where class = 'B'
     ) b
     on a.seqnum = b.seqnum full outer join
     (select name, row_number() over (order by (select NULL)) as seqnum
      from nameclasses nc
      where class = 'c'
     ) c
     on c.seqnum = coalesce(a.seqnum, b.seqnum)
order by coalesce(a.seqnum, b.seqnum, c.seqnum);

答案 1 :(得分:1)

您要求的数据并非真正非常关系,在这些情况下,您通常可以通过在客户端应用程序中完成工作获得更好的结果。但由于这通常是不可能的:

SELECT A.Name as A, B.Name as B, C.Name AS C
FROM 
  (select Name, row_number over (order by name) as ordinal from table where class = 'A') A
FULL JOIN
  (select Name, row_number over (order by name) as ordinal from table where class = 'B') B
     ON B.ordinal = A.ordinal
FULL JOIN
  (select Name, row_number over (order by name) as ordinal from table where class = 'C') C
     ON C.ordinal = coalesce(A.ordinal, B.ordinal)

答案 2 :(得分:-2)

使用"组"请求结尾处的函数如下:"从a.tata"中选择一个组中的a.toto,a.tata。 http://www.w3schools.com/sql/sql_groupby.asp