sql - 在 SQL 中对具有多列和多行的表进行透视和反透视

标签 sql sql-server pivot pivot-table unpivot

我需要输出这个下表如下。 下面是现有的数据库表输出。

UNIQUE_ID   PARTICULARS                   18-Jan    18-Feb    18-Mar
-----       -----                         -----     -----     -----
1           Direct Cost                   3,393     3,776     3,776
1           Quarter                       Q3 FY18   Q3 FY18   Q3 FY18
1           Revenue net Volume Discount   4,409     5,787     5,512
2           Direct Cost                   25,022    39,178    34,143
2           Quarter                       Q2 FY18   Q2 FY18   Q2 FY18
2           Revenue net Volume Discount   28,730    45,507    38,247

我需要将上面的表格转换为下面的输出。

UNIQUE_ID   FinancialMonth  Quarter     DirectCost  Revenue net Volume Discount
1           18-Jan          Q3 FY18     3,393       4,409
1           18-Feb          Q3 FY18     3,776       5,787
1           18-Mar          Q3 FY18     3,776       5,512
2           18-Jan          Q2 FY18     25,022      28,730
2           18-Feb          Q2 FY18     39,178      45,507
2           18-Mar          Q2 FY18     34,143      38,247

你能帮我转换一下吗?我已使用 unpivot 转换 FinancialMonth,但无法将 Quarter 转换为 Column。

SELECT UNIQUE_ID
       ,PARTICULARS
       ,[FinancialYearMonth] AS 'FinancialMonth'
       ,CASE WHEN PARTICULARS='Direct Cost'   
             THEN [FinancialValues] END AS [DirectCost]
       ,CASE WHEN PARTICULARS='Revenue net Volume Discount'   
             THEN [FinancialValues] END AS [RevenueNetVolumeDiscount]

FROM DBO.Raw_Monthly
UNPIVOT   
  ( 
        FinancialValues
    FOR [FinancialYearMonth] IN(
       Jan18
      ,[Feb18]
      ,[Mar18]


       ) 
   ) AS unpv 

在上面的查询中缺少季度值。

根据我的理解,FinancialMonthQuarter 都可能是逆轴和轴轴。你能帮忙解决这个问题吗?

最佳答案

尝试过的查询在unpivoting 之后缺少pivoting(条件聚合,例如case..when 包含通过分组聚合的子句) 。因此,请考虑:

 SELECT [Unique_ID], [FinancialMonth], 
        MAX(CASE WHEN [Particulars]='Quarter' THEN [FinancialValues] END) AS [Quarter],
        MAX(CASE WHEN [Particulars]='Direct Cost' THEN [FinancialValues] END) AS [DirectCost],
        MAX(CASE WHEN [Particulars]='Revenue net Volume Discount' THEN [FinancialValues] 
        END) AS [Revenue net Volume Discount]
   FROM Raw_Monthly
UNPIVOT  
   (
    [FinancialValues] FOR [FinancialMonth] IN ( [18-Jan] ,[18-Feb] ,[18-Mar] ) 
   ) AS unpvt
  GROUP BY [Unique_ID], [FinancialMonth]
  ORDER BY [Unique_ID], 
           CONVERT(date, REVERSE(SUBSTRING(REVERSE([FinancialMonth]),1,3))+
                  ' 20'+  SUBSTRING(REPLACE([FinancialMonth],'-',''),1,2) , 13)

Demo

关于sql - 在 SQL 中对具有多列和多行的表进行透视和反透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567589/

相关文章:

sql - 百分比行占总计,其中每行由 group by 子句确定

sql-server - 如何引发 SQL 将视为作业失败的错误?

php - H 型 : illegal hex digit x

sql-server - SQL Server 2012 Management Studio Intellisense 无法通过 VPN 工作

Pandas 数据透视表显示每个条目的行数相等

sql - 为什么 Postgres 在此查询中执行哈希?

php - SQL 查询以显示最接近特定事件的数据

mysql - SQL 查询抛出错误 150

mysql - 如何建立具有多个一对多关系的数据库?使用数据透视表或连接表?

mysql - 如何在具有多个条件的MySql中获取计数