按类别分组并添加额外的列

时间:2018-03-25 08:35:21

标签: sql sql-server group-by subquery inner-join

很抱歉,如果标题不够具有描述性。所以我决定上传照片。

我想知道将表1转换为表2的最有效方法。目前我内部加入一些子查询,我觉得这不是最好的方法。

table 1

table 2

1 个答案:

答案 0 :(得分:1)

首先,数据定义(因为你没有提供任何插入查询,我编写了用于生成它的脚本):

declare @table table(issueDsc varchar(20), cfName varchar(20), cfValue varchar(20))
insert into @table values
('cat 11.1 text1','Location','Sydney'),
('cat 11.1 text1','MC Response Date',null),
('cat 11.1 text1','VPR','no'),
('cat 11.1 text2','Location','Melbourne'),
('cat 11.1 text2','MC Response Date',null),
('cat 11.1 text2','VPR',null),
('cat 11.1 text3','Location',null),
('cat 11.1 text3','MC Response Date','2018-03-24'),
('cat 11.1 text3','VPR','yes')

此处查询,这将产生您想要的记录集:

--catDsc is fetched from between cat and text word (achieved with charindex functions)
select substring(issueDsc, charindex('cat', issueDsc) + 3, charindex('text', issueDsc) -charindex('cat', issueDsc)- 4) [catDsc],
       [issueDsc],
       [Location],
       [VPR],
       [MC Response Date] 
from @table
--syntax for this part is very simple and you could goole it in order to better understand
pivot
(
    MAX(cfValue)
    for cfName in ([Location],[VPR],[MC Response Date])
) as pivoted