【问题标题】:Pivoting data with CASE expression使用 CASE 表达式透视数据
【发布时间】:2020-08-01 06:37:08
【问题描述】:

我有以下查询,它获取商店、周数和售出产品的总和:

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;

CASE 表达式是否可以得到相同的结果?

【问题讨论】:

标签: sql sql-server tsql pivot aggregate-functions


【解决方案1】:

您可以按如下方式使用条件聚合进行透视:

select 
    store, 
    sum(case when week = 1 then xcount else 0 end) week1,
    sum(case when week = 2 then xcount else 0 end) week2,
    sum(case when week = 3 then xcount else 0 end) week3
from yt
group by store

我更喜欢条件聚合而不是特定于数据库的 pivot 语法:

  • 条件聚合比pivot更灵活

  • 该语法适用于大多数数据库,因此更便携

  • 性能通常相当

【讨论】:

  • 你如何描述灵活性?
  • @mo-mhi:假设您想要另一列对第 2 周和第 3 周的值求和。使用条件聚合,使用 sum(case when week in (2, 3) then xcount else 0 end) week2_and_week3 很容易做到,而使用 pivot 这将是复杂得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
相关资源
最近更新 更多