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

How to use the PIVOT or UNPIVOT T-SQL syntax to achieve this output?

我的 SQL 服务器数据库中有以下 table。

  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 查询来转换这个 table(我们称之为 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)的需求感到困惑(如果这是正确的方法)这样做!)。

您需要使用PIVOT

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

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

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  

Prdp 的回答很准确。以下是为了以防万一你需要动态

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);

Returns

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