以文本方式查看主题

-  Foxtable(狐表)  (http://www.foxtable.com/bbs/index.asp)
--  专家坐堂  (http://www.foxtable.com/bbs/list.asp?boardid=2)
----  求一sql语句  (http://www.foxtable.com/bbs/dispbbs.asp?boardid=2&id=25690)

--  作者:zharen110
--  发布时间:2012/11/14 16:26:00
--  求一sql语句
我用的是sqlserver2000[code=sql]
CREATE TABLE [prices] (
[id] [int] IDENTITY (1, 1) NOT NULL ,         --编号
[good_id] [int] NULL ,                        --物品编号
[price] [float] NULL ,                        --物品单价
[m] [int] NULL ,                              --价格变动月份
[y] [int] NULL ,                              --价格变动年份
[updatetime] [datetime] NULL ,                --更新时间
CONSTRAINT [PK_prices] PRIMARY KEY  CLUSTERED 
(
[id]
)  ON [PRIMARY] 
) ON [PRIMARY]
GO

insert into prices(good_id,price,m,y,updatetime) values(1,1.3,1,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(1,1.5,2,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(1,1.6,4,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(1,2.3,6,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(1,4.3,8,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(2,7.3,1,2012,\'2012-11-11\')
insert into prices(good_id,price,m,y,updatetime) values(2,8.3,2,2012,\'2012-11-11\')
[/code]

要查询出以下效果
[code=sql]
good_id  1月  2月  3月  4月  5月  6月  7月  8月  9月  10月  11月  12月 
      1     1.3  1.5        1.6        2.3        4.3  
      2     7.3  8.3        
每个good_id一条记录  查询出每种物品2012年每个月价格变动情况
[/code]
[此贴子已经被作者于2012-11-14 16:28:04编辑过]

--  作者:lin_hailun
--  发布时间:2012/11/14 17:19:00
--  
 在网上查了下,终于是找到了。

select good_id,
一月 = max(case when m = 1 then price else null end ),
二月 = max(case when m = 2 then price else null end ),
三月 = max(case when m = 3 then price else null end ),
四月 = max(case when m = 4 then price else null end ),
五月 = max(case when m = 5 then price else null end ),
六月 = max(case when m = 6 then price else null end ),
七月 = max(case when m = 7 then price else null end ),
八月 = max(case when m = 8 then price else null end ),
九月 = max(case when m = 9 then price else null end ),
十月 = max(case when m = 10 then price else null end ),
十一月 = max(case when m = 11 then price else null end ),
十二月 = max(case when m = 12 then price else null end )
from prices group by good_id
[此贴子已经被作者于2012-11-14 17:19:21编辑过]

--  作者:zharen110
--  发布时间:2012/11/14 17:54:00
--  
不错,谢谢了