【问题标题】:Pivot Double Sum枢轴双和
【发布时间】:2019-03-29 07:49:46
【问题描述】:

我正在使用此选择来获取列价格的数据透视。没关系,但我也想对列 M1、M2 和 M3、M4 求和。

SELECT *,25 M1Cijena, 25 M2Cijena, 16 M3Cijena, 16 M4Cijena
FROM (
    select u.pin Pin,u.firstname Name,u.lastname,sum(tmt.Price) Prices, tmt.type MealType
    from TA_Meals tm
    left outer join TA_MealsType tmt
    on tm.MealType = tmt.id     
    full outer join users u
    on u.pin = tm.pin
    where u.department = 1000001001
    group by u.pin,u.firstname,u.lastName,tmt.Type  
) as s
PIVOT
(
    SUM(Prices)
    FOR MealType IN (M1,M2,M3,M4)  **<-- here also want sum for M1,M2 and M3,M4.**

)AS pvt

【问题讨论】:

  • 我正在使用 SQL Server
  • 您当然可以在SELECT 子句中将总和相加吗?上次我检查时,SUM(M1+M2)SUM(M1)+SUM(M2) 产生了相同的结果(不包括 null 处理问题)
  • 我得到空值。

标签: sql sql-server tsql pivot


【解决方案1】:

为什么不只使用条件聚合?

select u.pin, u.firstname, u.lastname,
      sum(case when tmt.type = 'M1' then tmt.Price end) as m1,
      sum(case when tmt.type = 'M2' then tmt.Price end) as m2,
      sum(case when tmt.type = 'M3' then tmt.Price end) as m3,
      sum(case when tmt.type = 'M4' then tmt.Price end) as m4,
      sum(case when tmt.type in ('M1', 'M2') then tmt.Price end) as m1_2,
      sum(case when tmt.type in ('M3', 'M4') then tmt.Price end) as m3_4
from users u left join
     TA_Meals tm
     on u.pin = tm.pin left join
     TA_MealsType tmt
     on tm.MealType = tmt.id join
where u.department = 1000001001
group by u.pin, u.firstname, u.lastName;

请注意,我还修复了您的联接,因此更有意义。将where 与外连接一起使用通常会影响正在实现的连接类型。

【讨论】:

  • 很好的解决方案!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 2018-05-16
相关资源
最近更新 更多