从一张表透视数据

时间:2019-04-09 08:51:55

标签: sql sql-server pivot

输入表

country tag short
UK  F1  Units
UK  F2  Volume
UK  F3  Value
FR  T3  Units
FR  T2  Volume
FR  T1  Value

我想要的结果输出:

country Units Volume Value
uk      f1      f2      f3
fr      t1      t2      t3

3 个答案:

答案 0 :(得分:1)

如果有固定数量的不同short值,只需使用case表达式进行条件聚合

select country,
       max(case when short = 'Units' then tag end) as Units,
       max(case when short = 'Volume' then tag end) as Volume,
       max(case when short = 'Value' then tag end) as val
from tablename
group by country

答案 1 :(得分:1)

对于解决方案,您必须使用动态数据透视。

//to expand the buttons:
topFab.animate().rotationBy(180);
fab2.animate().translationY(-150);
fab3.animate().translationY(-300);
fab4.animate().translationY(-450);

//to collapse them:
topFab.animate().rotationBy(-180);
fab2.animate().translationY(0);
fab3.animate().translationY(0);
fab4.animate().translationY(0);

答案 2 :(得分:0)

表结构

 CREATE TABLE tablename
  (
     [country] [NVARCHAR](10) NULL,
     [tag]     [NVARCHAR](10) NULL,
     [short]   [NVARCHAR](10) NULL
  )

INSERT INTO tablename
VALUES      
('UK','F1','Units'),
('UK','F2','Volume'),
('UK','F3','Value'),
('FR','T3','Units'),
('FR','T2','Volume'),
('FR','T1','Value');

使用数据透视功能

SELECT *
FROM   tablename
       PIVOT ( Max(tag)
             FOR short IN ([Units], [volume], [Value]) ) piv;  

在线演示:Link

使用动态SQL PIVOT

DECLARE @cols  AS NVARCHAR(max),
        @query AS NVARCHAR(max)

SELECT @cols = Stuff((SELECT distinct ',' + Quotename(short)
                      FROM   tablename
                      FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1,'');

SET @query = 'SELECT * 
              FROM   tablename        
                     PIVOT ( Max(tag)              
                           FOR short IN (' + @cols + ') ) piv;';

EXECUTE(@query);  

在线演示:Link

结果

+---------+-------+--------+-------+
| country | Units | volume | Value |
+---------+-------+--------+-------+
| FR      | T3    | T2     | T1    |
| UK      | F1    | F2     | F3    |
+---------+-------+--------+-------+