简体   繁体   English

使用 CASE 表达式透视数据

[英]Pivoting data with CASE expression

I have the following query which gets the store, the week number and the sum of products sold:我有以下查询,它获取商店、周数和售出产品的总和:

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

Is it possible to get the same result with CASE expression?是否可以使用 CASE 表达式获得相同的结果?

You can pivot with conditional aggregation as follows:您可以使用条件聚合 pivot 如下:

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

I tend to prefer conditional aggregation over database-specific pivot syntaxes:我倾向于使用条件聚合而不是特定于数据库的pivot语法:

  • conditional aggregation is more flexible than pivot条件聚合比pivot更灵活

  • the syntax works across most databases, so it is much more portable该语法适用于大多数数据库,因此更便携

  • performance is usually equivalent性能通常相当

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM