日期:2014-05-18  浏览次数:20450 次

SQL行转列、、、、急,急。正确答案,分数全部是你的。
现有表【hong_prop】,里面的字段为以下这些:
  游戏类型<gametype>,游戏区<arrea>,时间<regtime>,金币类型<type>,道具名称<Propname>,销售次数<cvount>



  表中的测试数据为 :
 gametype arrea regtime type Propname count
  1 1 2011-12-22 绑定金币 二档绑定石 23
  1 1 2011-12-21 绑定金币 极品的物攻宝石 11
  1 1 2011-12-20 绑定金币 度世丹 1
  1 1 2011-12-19 绑定金币 二档绑定石 2 
  1 1 2011-12-18 绑定金币 极品的物攻宝石 10
  1 1 2011-12-18 绑定金币 六档升星石 3
  1 1 2011-12-17 绑定金币 极品的物攻宝石 13
  1 1 2011-12-17 绑定金币 六档升星石 15
  1 1 2011-12-17 绑定金币 极品的物攻宝石 1
  1 1 2011-12-16 绑定金币 度世丹 2
  1 1 2011-12-16 绑定金币 二档绑定石 14
  1 1 2011-12-15 绑定金币 六档升星石 1
  1 1 2011-12-14 绑定金币 度世丹 5
  1 1 2011-12-14 绑定金币 度世丹 6
  1 1 2011-12-14 绑定金币 二档绑定石 8
  1 1 2011-12-14 绑定金币 二档绑定石 10
  1 1 2011-12-13 绑定金币 极品的物攻宝石 11
  1 1 2011-12-12 绑定金币 二档绑定石 12


现在我需要一条SQL语句,查询出每天销售的道具情况。用时间作为行,商城道具作为列,且只查询最近一周的数据;

想要的最后结果是这样子的:

  名称 2011-12-22 2011-12-21 2011-12-20 2011-12-19 2011-12-18 2011-12-17 2011-12-16
  度世丹 0 0 1 0 0 0 2 
 二档绑定石 23 0 0 2 0 0 14
 六档升星石 0 0 0 0 3 15 14
极品的物攻宝石 0 11 0 0 10 14 0





谢啦,语句正确,分数全部归你。

------解决方案--------------------
示例:
select Propname,sum(case when arrea='2011-12-22' then count end),
sum(case when arrea='2011-12-21' then count end),
...
sum(case when arrea='2011-12-16' then count end)
from tt group by Propname
------解决方案--------------------
示例:
假设有张学生成绩表(CJ)如下
Name Subject Result
张三 语文 80
张三
数学 90
张三 物理 85
李四 语文 85
李四 数学
92
李四 物理 82

想变成
姓名 语文 数学 物理
张三 80 90 85
李四 85 92
82

declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql 
+ ',sum(case Subject when '''+Subject+''' then Result end) 
['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = 
@sql+' from test group by name'
exec(@sql)

自行修改
------解决方案--------------------
declare @sql varchar(4000);
set @sql = 'select Propname';
select @sql = @sql
+ ',sum(case when regtime='''+aa+''' then count else 0 end) as 
['+aa+']'
from (select distinct CONVERT(CHAR(10),regtime,120) as aa from hong_prop) as a;
select @sql =
@sql+' from hong_prop group by Propname';
select @sql;
 exec(@sql);

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[gametype] int,
[arrea] int,
[regtime] date,
[type] varchar(8),
[Propname] varchar(14),
[count] int
)
go
insert [test]
select 1,1,'2011-12-22','绑定金币','二档绑定石',23 union all
select 1,1,'2011-12-21','绑定金币','极品的物攻宝石',11 union all
select 1,1,'2011-12-20','绑定金币','度世丹',1 union