一直以为已经写过这个博客的。。。结果没有
1. 首先你要找到你是根据什么分组(group by),也就是通常
第一列会什么呢
举个例子呢:
========》
以什么分组呢?肯定是名字的啦!!!
再举个例子:===>
这个又会要已什么分组呢?毫无疑问是RoomTypeCode
这时候你会写出group by 的语句出来,比如上面的两例应该会是这样子:
select 姓名 from tb group by 姓名
select RoomTypeCode from YearRoomPrice group by RoomTypeCode
这时候我们第一列已经有了
2. 我们需要第二列了(行转列精髓了)
select 姓名 from tb group by 姓名
在上面的sql语句上我们要加些东西了,这时候我们想一下为什么group by中一般看其他列都是需要加上sum,max,min等等,因为这个列内容有许多,要分组,只能取一个,但其实select已经取出所有符合条件的了,现只需要将取出的数据处理下即可
select 姓名,
max(case when 课程='语文' then 分数 else 0 end) as '语文', --我们这里else的情况都为0,就是因为0是最小的
max(case when 课程='数学' then 分数 else 0 end) as '数学',
max(case when 课程='物理' then 分数 else 0 end) as '物理'
from tb group by 姓名
另一个情况也是这样的
select max(yrp.HotelID) as HotelID,max(yrp.RoomTypeCode) as RoomTypeCode,
max(case BizDate when '2014-11-05' then MarketPrice else 0 end) as '2014-11-05',
max(case BizDate when '2014-11-06' then MarketPrice else 0 end) as '2014-11-06',
max(case BizDate when '2014-11-07' then MarketPrice else 0 end) as '2014-11-07',
max(case BizDate when '2014-11-08' then MarketPrice else 0 end) as '2014-11-08',
max(case BizDate when '2014-11-09' then MarketPrice else 0 end) as '2014-11-09'
from YearRoomPrice yrp where HotelID='020046' and BizDate>='2014-11-05' and BizDate<='2014-11-09'
group by RoomTypeCode
相信大家都能看懂的
3. 其实很多时候大家也不能确定需要分出多少列来,可以适用sql拼接的方式来做
declare @sql varchar(8000)
declare @beginDate varchar(100)
declare @endDate varchar(100)
declare @hotelID varchar(20)
set @beginDate='2014-11-05'
set @endDate='2014-11-09'
set @hotelID='020046'
set @sql=' select max(yrp.HotelID) as HotelID,max(yrp.RoomTypeCode) as RoomTypeCode '
select @sql = @sql + ',max(case BizDate when '''+CONVERT(varchar(100),BizDate,23) +''' then MarketPrice else 0 end) as '''+CONVERT(varchar(100),23)+''''
from (
select distinct BizDate from YearRoomPrice where HotelID=@hotelID and BizDate>=@beginDate and BizDate<=@endDate
) as a
--这里红色字的部分可以达到一个循环的作用
set @sql = @sql+ 'from YearRoomPrice yrp where HotelID='''
+@hotelID+''' and BizDate>='''
+@beginDate+''' and BizDate<='''
+@endDate+'''group by RoomTypeCode'
print @sql
exec(@sql)
上面的sql语句print是这样的
select max(yrp.HotelID) as HotelID,
max(case BizDate when '2014-11-05' then MarketPrice else 0 end) as '2014-11-05',
max(case BizDate when '2014-11-06' then MarketPrice else 0 end) as '2014-11-06',
max(case BizDate when '2014-11-07' then MarketPrice else 0 end) as '2014-11-07',
max(case BizDate when '2014-11-08' then MarketPrice else 0 end) as '2014-11-08',
max(case BizDate when '2014-11-09' then MarketPrice else 0 end) as '2014-11-09'
from YearRoomPrice yrp where HotelID='020046' and BizDate>='2014-11-05' and BizDate<='2014-11-09'
group by RoomTypeCode
好了,大概就是这样了。。。