在数据透视表中连接列名称

时间:2015-09-18 15:53:24

标签: sql sql-server sql-server-2012 pivot

我的新情况。我需要从表中转动2列的串联结果。例如,我可以转动以下内容:

CREATE TABLE #pivSource(
ID INT,
Name VARCHAR(50),
Acronym VARCHAR(20),
[Type] VARCHAR(50)
)

INSERT INTO #pivSource(ID, Name, Acronym, [Type])
SELECT 1, 'Emily','ABC',  'A'
UNION 
SELECT 2, 'Lorenzo','DEF',  'B' 
UNION
SELECT 3, 'Estelle','GHI',  'C'
UNION
SELECT 4, 'Rosie','JKL',  'D'
UNION
SELECT 5, 'Paula','MNO',  'E'
UNION
SELECT 6, 'Rick', 'PQR',  'F'
UNION
SELECT 7, 'Elvira','STU',  'G'
UNION
SELECT 8, 'Eva','VWX',  'H'
UNION
SELECT 9, 'Erick','YZ0',  'I'

SELECT * FROM #pivSource

为您提供以下结果集:

ID  Name    Acronym Type
1   Emily   ABC A
2   Lorenzo DEF B
3   Estelle GHI C
4   Rosie   JKL D
5   Paula   MNO E
6   Rick    PQR F
7   Elvira  STU G
8   Eva VWX H
9   Erick   YZ0 I

我想在一个pivot中连接一个列,它会给出一个像这样的结果集:

ID  ABCA  DEFB   GHIC   JKLD   MNLE   PQRF   STUG   VWXH   YZ0I
1   1     0      0      0      0      0      0      0      0
2   0     1      0      0      0      0      0      0      0        
3   0     0      1      0      0      0      0      0      0    
4   0     0      0      1      0      0  0      0      0
5   0     0      0      0      1      0      0      0      0    
6   0     0      0      0      0      1      0      0      0    
7   0     0      0      0      0      0      1      0      0    
8   0     0      0      0      0      0      0      1      0    
9   0     0      0      0      0      0      0      0      1

本质上我想做这样的事情:

SELECT 
    * 
FROM 
    #pivSource
PIVOT 
    (COUNT(Name)  
    FOR Acronym + [Type] IN(
        [ABC] + [A],
        [DEF] + [B],
        [GHI] + [C],
        [JKL] + [D],
        [MNO] + [E],
        [PQR] + [F],
        [STU] + [G],
        [VWX] + [H],
        [YZ0] + [I])
) AS PivAcrnmType ORDER BY ID;

这不起作用,也不用逗号分隔(即...FOR Acronym , [Type] IN(...。有任何建议吗?

2 个答案:

答案 0 :(得分:1)

你在转动之前试过连接吗?

SELECT 
    * 
FROM 
    (select *, Acronym + [Type] as acronym_type
     from #pivSource) p
PIVOT 
    (COUNT(Name)  
    FOR acronym_type IN(
        'ABCA',
        'DEFB',
        'GHIC',
        'JKLD',
        'MNOE',
        'PQRF',
        'STUG',
        'VWXH',
        'YZ0I')
) AS PivAcrnmType ORDER BY ID;

答案 1 :(得分:1)

使用子查询或CTE连接,然后使用PIVOT:

<强> SqlFiddle

;WITH cte
AS
(
  SELECT
      Id,
      Name,
      AcronymType =  Acronym + Type
  FROM pivSource
)
SELECT * 
FROM  cte
PIVOT 
(
    COUNT(Name)  
    FOR AcronymType IN(
        [ABCA],
        [DEFB],
        [GHIC],
        [JKLD],
        [MNOE],
        [PQRF],
        [STUG],
        [VWXH],
        [YZ0I])
) AS PivAcrnmType
 ORDER BY ID;