请告诉我如何编写一个独特的sql语句

时间:2012-07-24 18:07:44

标签: sql sql-server select

下面是我需要从中提取数据的表格 - 我在此示例中仅包含了要使用的列:

Maintable

mainkey, account
-----------------
1, 100
2, 200
3, 300

Childtable

linkedkeytomain, type, color
---------------------------
2, b, blue
2, y, yellow
2, r, red
2, g, green
2, w, white

我的目标是能够编写一个仅显示一行数据的选择,其中Type ='b'和Type ='w'且Type ='r'仅限:

例如,

Account, c1, c2, c3
---------------------
200, blue, white, red

有人可以告诉我如何获得这个复杂的选择。非常感谢提前。

blumonde

1 个答案:

答案 0 :(得分:1)

您的问题是您需要透视组。这是一个简单的方法:

select account,
       max(case when seqnum = 1 then color end) as color1,
       max(case when seqnum = 2 then color end) as color2,
       max(case when seqnum = 3 then color end) as color3
from (select account, color,
             row_number() over (partition by account order by color) as seqnum
      from maintable mt join
           childtable ct
           on ct.linkedkeytomain = mt.mainkey
     ) t
group by account