这个问题都是关于SQL Azure的。我有一个按年划分的各种商品价格和单价的数据集,如下所示:
大米- 2007 - 0.5
大米- 2007 - 0.3
大米- 2007 - 0.8
小麦- 2006 - 1.1
小麦- 2006 - 1.4
等
我如何创建一个透视表,给出每种商品每年支付的最高和最低价格?我知道如何做一个类似平均值的数据透视表--这很容易。但是我需要我的“主轴”列是年份,然后每年都会有2个“子列”,表示最小价格和最大价格,我不太确定如何做到这一点。帮助!
发布于 2013-04-04 23:58:40
除非我在你的解释中遗漏了什么,否则你可以很容易地做到这一点,而不使用PIVOT函数:
select product,
year,
min(price) MinPrice,
max(price) MaxPrice
from yourtable
group by product, year参见SQL Fiddle with Demo。
如果您想将数据放在单独的列中,那么有几种方法可以做到这一点。
具有CASE:的聚合函数
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的新列,然后透视:
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。这些结果如下所示:
| PRODUCT | 2006_MINPRICE | 2006_MAXPRICE | 2007_MINPRICE | 2007_MAXPRICE |
---------------------------------------------------------------------------
| Rice | 0 | 0 | 0.3 | 0.8 |
| Wheat | 1.1 | 1.4 | 0 | 0 |如果你有一个未知的年数,那么你也可以实现动态sql。
https://stackoverflow.com/questions/15815893
复制相似问题