首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL Azure -创建复杂透视表

SQL Azure -创建复杂透视表
EN

Stack Overflow用户
提问于 2013-04-04 23:49:27
回答 1查看 1.3K关注 0票数 0

这个问题都是关于SQL Azure的。我有一个按年划分的各种商品价格和单价的数据集,如下所示:

大米- 2007 - 0.5

大米- 2007 - 0.3

大米- 2007 - 0.8

小麦- 2006 - 1.1

小麦- 2006 - 1.4

我如何创建一个透视表,给出每种商品每年支付的最高和最低价格?我知道如何做一个类似平均值的数据透视表--这很容易。但是我需要我的“主轴”列是年份,然后每年都会有2个“子列”,表示最小价格和最大价格,我不太确定如何做到这一点。帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-04 23:58:40

除非我在你的解释中遗漏了什么,否则你可以很容易地做到这一点,而不使用PIVOT函数:

代码语言:javascript
复制
select product,
  year,
  min(price) MinPrice,
  max(price) MaxPrice
from yourtable
group by product, year

参见SQL Fiddle with Demo

如果您想将数据放在单独的列中,那么有几种方法可以做到这一点。

具有CASE:的聚合函数

代码语言:javascript
复制
select product,
  min(case when year=2006 then price else 0 end) [2006_MinPrice],
  max(case when year=2006 then price else 0 end) [2006_MaxPrice],
  min(case when year=2007 then price else 0 end) [2007_MinPrice],
  max(case when year=2007 then price else 0 end) [2007_MaxPrice]
from yourtable
group by product

请参阅SQL Fiddle with Demo

UNPIVOT和PIVOT:

UNPIVOT用于将列数据转换为行。在行中,您可以创建包含year的新列,然后透视:

代码语言:javascript
复制
select *
from
(
  select product, 
    cast(year as varchar(4))+'_'+col as piv_col,
    value
  from
  (
    select product,
      year,
      min(price) MinPrice,
      max(price) MaxPrice
    from yourtable
    group by product, year
  ) x
  unpivot
  (
    value for col in (minPrice, maxPrice)
  ) u
) d
pivot
(
  max(value)
  for piv_col in ([2006_MinPrice], [2006_MaxPrice],
                  [2007_MinPrice], [2007_MaxPrice])
) piv;

参见SQL Fiddle with Demo。这些结果如下所示:

代码语言:javascript
复制
| PRODUCT | 2006_MINPRICE | 2006_MAXPRICE | 2007_MINPRICE | 2007_MAXPRICE |
---------------------------------------------------------------------------
|    Rice |             0 |             0 |           0.3 |           0.8 |
|   Wheat |           1.1 |           1.4 |             0 |             0 |

如果你有一个未知的年数,那么你也可以实现动态sql。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15815893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档