除非我在您的解释中遗漏了某些内容,否则您可以在没有 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
UNPIVOT 和 PIVOT:
UNPIVOT 用于将列数据转换为行。进入行后,您可以使用年份创建新列,然后进行透视:
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。