Foxtable(狐表)用户栏目专家坐堂 → 求一sql语句


  共有8608人关注过本帖树形打印复制链接

主题:求一sql语句

帅哥哟,离线,有人找我吗?
zharen110
  1楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:幼狐 帖子:195 积分:2069 威望:0 精华:0 注册:2011/6/29 19:14:00
求一sql语句  发帖心情 Post By:2012/11/14 16:26:00 [只看该作者]

我用的是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
  2楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:狐神 帖子:6708 积分:34304 威望:0 精华:11 注册:2012/8/18 23:10:00
  发帖心情 Post By: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
  3楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:幼狐 帖子:195 积分:2069 威望:0 精华:0 注册:2011/6/29 19:14:00
  发帖心情 Post By:2012/11/14 17:54:00 [只看该作者]

不错,谢谢了 

 回到顶部