Pivot Double Sum - PullRequest
       11

Pivot Double Sum

0 голосов
/ 29 марта 2019

Я использую этот выбор, чтобы получить пивот для столбца Цены. Это нормально, но я также хочу сделать сумму для столбцов 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 голосов
/ 29 марта 2019

Почему бы просто не использовать условное агрегирование?

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 с внешними объединениями часто влияет на тип реализуемого объединения.

...