如何使用SQL Server中的一列在数据透视表中创建多个聚合列?

时间:2017-07-11 18:21:42

标签: sql sql-server tsql stored-procedures pivot

我希望按年显示成本和销售额。

错误消息:

  

专栏名称" 2016"在PIVOT运算符中指定的与PIVOT参数中的现有列名冲突。

     

专栏名称" 2017"在PIVOT运算符中指定的与PIVOT参数中的现有列名冲突。

     

专栏' 2016'被多次指定为' pivSales'。

注意

  

我可以理解为什么它显示错误,但我不知道在我的场景中获得输出的方法。

1 个答案:

答案 0 :(得分:4)

不需要PIVOT。只需应用条件聚合

select 
    StoreID,
    Department.Name Department,
    Category.Name Category, 
    Sum(case when Year(Time)=2016 then ExtendedCost end) [Cost(2016)],
    Sum(case when Year(Time)=2017 then ExtendedCost end) [Cost(2017)],
    Sum(case when Year(Time)=2016 then ExtendedPrice end) [Sales(2016)],
    Sum(case when Year(Time)=2017 then ExtendedPrice end) [Sales(2017)],
from F_itemDailySalesParent
Inner join item with(Nolock) on item.id = F_itemDailySalesParent.ItemID
Left join Department with(Nolock) on Department.ID = item.DepartmentID
Left join Category with(Nolock) on Category.ID =item.CategoryID
where DATEPART(yyyy,Time) in (2016,2017)
group by StoreID,Department.Name,Category.Name
order by StoreID
  

编辑 - 使用原始查询并应用PIVOT

Select *
 From (
        Select StoreID
              ,Department
              ,Category
              ,B.*
         From (
                select 
                    DATEPART(yyyy,Time) Years,
                    StoreID,
                    Department.Name Department,
                    Category.Name Category, 
                    Sum(ExtendedCost) Cost,
                    sum(ExtendedPrice) Sales
                from F_itemDailySalesParent
                Inner join item with(Nolock) on item.id = F_itemDailySalesParent.ItemID
                Left join Department with(Nolock) on Department.ID = item.DepartmentID
                Left join Category with(Nolock) on Category.ID =item.CategoryID
                where DATEPART(yyyy,Time) in (2016,2017)
                group by DATEPART(yyyy,Time),StoreID,Department.Name,Category.Name
              ) A
         Cross Apply ( values (concat('cost(',Years,')'),Cost)
                             ,(concat('sales(',Years,')'),Sales)
                     ) B (Item,Value)
      ) src
 Pivot (sum[Value]) For [Item] in ([cost(2016)],[cost(2017)],[sales(2016)],[sales(2017)] ) p