首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态枢轴两列前缀

动态枢轴两列前缀
EN

Stack Overflow用户
提问于 2017-03-30 15:38:25
回答 2查看 124关注 0票数 0

数据库: 2012

我有一张桌子,里面有电脑和安装的软件。现在,一台计算机可以安装30+软件,但是基础结构上可能有不同的100+软件。

这是表的表示形式。

代码语言:javascript
复制
Computer  | Software
--------------------
PC123     | Office
PC123     | Firefox
PC456     | Office
PC456     | Firefox
PC456     | CAD
PC789     | Firefox
PC789     | Outlook
...

我在找一个像这样的结果

代码语言:javascript
复制
Computer  | Software 1 | Software 2 | Software 3 
------------------------------------------------
PC123     | Firefox    | Office     | NULL
PC456     | CAD        | Firefox    | Office
PC789     | Firefox    | Outlook    | NULL
...

我一直在研究动态支点,但我仍然对SQL很陌生。

谢谢你的帮助

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-30 15:56:26

这里有无数的动态转向的例子,然而,我理解有时候我们都需要一个小小的启动。

示例

代码语言:javascript
复制
Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('Software ',Row_Number() over (Partition By Computer Order By Software))) From Yourtable  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [Computer],' + @SQL + '
From (
       Select Computer
             ,Software
             ,Col      = concat(''Software '',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);

返回

代码语言:javascript
复制
Computer    Software 1  Software 2  Software 3
PC123       Firefox     Office      NULL
PC456       CAD         Firefox     Office
PC789       Firefox     Outlook     NULL

如果有帮助,生成的如下所示:

代码语言:javascript
复制
Select [Computer],[Software 1],[Software 2],[Software 3]
From (
       Select Computer
             ,Software
             ,Col      = concat('Software ',Row_Number() over (Partition By Computer Order By Software))
       From YourTable
     ) A
Pivot (max([software]) For [Col] in ([Software 1],[Software 2],[Software 3]) ) p
票数 1
EN

Stack Overflow用户

发布于 2017-03-30 16:12:51

另一种选择是使用stuff函数,并将所有软件放在一行中。我的代码可能有点错。我烂透了却不能测试。

代码语言:javascript
复制
Results should look like this:
Computer    Software
PC123       Firefox, CAD, Office        
PC456       Firefox


SELECT t.Computer, Software_String.Software
FROM (SELECT DISTINCT Computer FROM TABLE) t
OUTER APPLY (
SELECT REPLACE(STUFF((
            SELECT ', ' + w.Start_Date, 100) 
            FROM Computer w
            WHERE c.Computer_ID = w.Computer_ID
            FOR XML PATH('')
            ), 1, 2, ''), '  ', ' ') [Software]
        ) Software_String

或者您可以使用case语句而不是枢轴。我觉得枢轴编程很慢,写起来也很痛苦。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43122364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档