mssql创建将表连接到自身的视图

问题描述 投票:0回答:2

我有一张桌子如下:

itemid      details      color

t001        door         red

t002        gate         green

t002        gate         blue

我想将具有多种颜色/ itemid的项目组合到一行上。永远不会超过两种颜色

如此理想的输出:

itemid      details      color1     color2

t001        door         red

t002        gate         green      blue

我试图使用嵌套的select和top 1 bottom 1进行连接,但是无法正常工作

select itemid,t1.color,t2.color
from table1 t1 
join (
select top 1 color
from table1 where iteid=t1,itemid
) t2

欢迎任何建议,

sql-server self-join
2个回答
1
投票

没有经过测试,但这可能是一种方法:

Select      a.itemid,
            a.details,
            a.color1,
            a.color2
from        (           
            Select      itemid,
                        details,
                        color as color1,
                        (Select color from #table1 as b where b.itemid = a.itemid and b.color <> a.color)   as color2
                        , ROW_NUMBER()   OVER (PARTITION BY itemid ORDER BY details DESC)  rn
            from        #table1     as a
            ) as a
where       a.rn = 1    

2
投票

你需要的是group_concat()。它有助于显示用逗号分隔的多个值。你也可以将逗号分隔符更改为你想要的任何东西。通过给出一个分隔符关键字.Ex:

GROUP_CONCAT(颜色分离器'|')

select itemid,details,group_concat(color) 
from t1 group by itemid

检查这个输出SQL FIDDLE.Hope它有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.