枢轴双和

时间:2019-03-29 07:49:46

标签: sql sql-server tsql pivot

我正在使用此选择来获取“价格”列的枢纽。很好,但我也想对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

1 个答案:

答案 0 :(得分:0)

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

for (i in Games.Split){
  for (j in i){
    Alive = j[which(j[5] == 'y'),]
    j <- Alive
  }
}

请注意,我也修复了您的联接,因此更有意义。将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; 与外部联接一起使用通常会影响所实现的联接的类型。