需要Sql查询(可能是数据透视)

时间:2009-06-16 05:16:11

标签: sql pivot

我有如下表格,

Product Name   Price   Date
Apple          1.5     5/5/2009
Apple          3       5/6/2009
Apple          3.5     5/7/2009
Apple          2.5     5/8/2009
Apple          5.5     5/9/2009
Orange         10.5    5/5/2009
Orange         12.5    5/6/2009
Orange         7.5     5/7/2009
Orange         4.5     5/8/2009
Orange         5.5     5/9/2009

我需要输出如下:

Product Name  5/5/2009   5/6/2009    5/7/2009    5/8/2009  5/9/2009
Apple          1.5        3          3.5         2.5       5.5
Orange        10.5       12.5        7.5         4.5       5.5

也是日期增加栏也需要增加, 请帮助我

Vickees

2 个答案:

答案 0 :(得分:1)

答案取决于您使用的数据库,但您可能会受益于this post

请注意,这是一个非常受欢迎的问题。通过搜索相关主题,您将获得最佳服务。我认为你将获得许多不同观点的好处,而不仅仅是那时登录用户的观点。

答案 1 :(得分:1)

select [Product name], //Give me all of the Fruit
sum(case when date = '5/05/09' then Price end as [5/5/09], // Sum Case Allow for multiple record on the same day
sum(case when date = '5/06/09' then Price end as [5/6/09],
sum(case when date = '5/07/09' then Price end as [5/7/09],
sum(case when date = '5/08/09' then Price end as [5/8/09],
sum(case when date = '5/09/09' then Price end as [5/9/09]
from tblfruits
group by [Product Name]