如何使用PIVOT或UNPIVOT T-SQL语法来实现此输出?

时间:2016-12-16 09:51:32

标签: sql sql-server tsql pivot unpivot

我的SQL Server数据库中有以下表格。

  Mkt    Property    Cat    Description   Values     Date
Germany  JohnS Ltd   SUP    RN             150        JUL 16  
Germany  JohnS Ltd   SUP    RN             100        JUL 16
Germany  JohnS Ltd   DLX    RN              60        JUL 16
Germany  JohnS Ltd   DLX    REV             80        JUL 16
Germany  JohnS Ltd   DLX    REV             75        JUL 16

我需要我的T-SQL查询来转换这个表(让我们称之为TblA)并给我以下输出:

Mkt         Date       Property      Cat      RN     REV
Germany     JUL 16     JohnS Ltd     SUP      250      0
Germany     JUL 16     JohnS Ltd     DLX       60    155

我猜我应该使用PIVOT或UNPIVOT语法来实现这一点,但我对在PIVOT查询中聚合两个值(RN和REV)的需求感到困惑(如果这是正确的方法) !)。

3 个答案:

答案 0 :(得分:3)

您需要使用PIVOT

SELECT  Mkt, Date, Property, Cat, RN, REV
From yourtable
Pivot (sum([Values]) for Description in ([RN],[REV])) pv

考虑到Descriptions的数量是静态的,您需要使用Dynamic Pivot

答案 1 :(得分:1)

Prdp的回答很明显。以下是您需要动态

的情况
foreach (var user in users)
        {
            user.SexList=new SexList(){}
        }

返回

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(Description) From YourTable For XML Path('')),1,1,'') 
Select  @SQL = '
 Select [Mkt], [Date], [Property], [Cat],' + @SQL + '
  From  YourTable
 Pivot (Sum([Values]) For [Description] in (' + @SQL + ') ) p'
Exec(@SQL);

答案 2 :(得分:0)

Using Pivot :

CREATE TABLE #Details (Mkt VARCHAR(100),  Property VARCHAR(100),    Cat   
 VARCHAR(100),  _Description VARCHAR(100), _Values INT,_Date VARCHAR(100))

INSERT INTO #Details ( Mkt,    Property  ,  Cat  ,  _Description ,_Values ,  
_Date)
SELECT 'Germany','JohnS Ltd','SUP','RN',150,'JUL 16' UNION ALL  
SELECT 'Germany','JohnS Ltd','SUP','RN',100,'JUL 16' UNION ALL
SELECT 'Germany','JohnS Ltd','DLX','RN',60,'JUL 16' UNION ALL
SELECT 'Germany','JohnS Ltd','DLX','REV',80,'JUL 16' UNION ALL
SELECT 'Germany','JohnS Ltd','DLX','REV',75,'JUL 16' 

SELECT *
FROM 
(
  SELECT Mkt,    Property  ,  Cat  ,  _Description ,_Values , _Date
  FROM #Details
)A
PIVOT 
(
   SUM(_Values) FOR _Description IN ([RN],[REV]) 
)pvt