SQL Server数据库动态交叉表的参考示例

作者:Alizze 时间:2009-01-04 14:44:00 

SQL Server数据库动态交叉表的参考示例:

--建立测试环境

set nocount on

create table test(model varchar(20),date int ,qty int)

insert into test select 'a','8','10'

insert into test select 'a','10','50'

insert into test select 'b','8','100'

insert into test select 'b','9','200'

insert into test select 'b','10','100'

insert into test select 'c','10','200'

insert into test select 'd','10','300'

insert into test select 'e','11','250'

insert into test select 'e','12','100'

insert into test select 'f','12','150'

go

--测试

declare @sql varchar(8000)

set @sql='select model,'

select @sql=@sql+'sum(case when

date='''+cast(date as varchar(10))+''' then qty else 0 end)

['+cast(date as varchar(10))+'],'

from (select distinct top 100 percent  date

 from test order by date)a

set @sql =left(@sql,len(@sql)-1)+' from test group by model'

exec(@sql)

--删除测试环境
drop table test
 set nocount off

/**//*
model                8           9           10          11          12
-------------------- ----------- ----------- ----------- ----------- -----------
a                    10          0           50          0           0
b                    100         200         100         0           0
c                    0           0           200         0           0
d                    0           0           300         0           0
e                    0           0           0           250         100
f                    0           0           0           0           150
*/

标签:
0
投稿

猜你喜欢

  • 谈中国站长站的文章干扰码实现方法

    2007-10-13 11:13:00
  • CSS高级文字排版的实例

    2009-03-24 20:56:00
  • HTML5 离线存储之Web SQL

    2011-06-19 14:13:19
  • asp数字或者字符排序函数代码

    2011-02-24 11:00:00
  • 一个奇怪的CSS现象

    2010-02-10 12:28:00
  • 获得当前数据库对象依赖关系的实用算法

    2009-01-08 13:28:00
  • asp获取文件md5值

    2008-10-13 09:10:00
  • 解决MySQL 5数据库连接超时问题

    2009-03-25 15:24:00
  • asp开发Wap中的随笔

    2008-05-21 12:56:00
  • 简析 IOS 程序图标的设计

    2011-04-28 09:39:00
  • PHP正则表达式替换<pre>标签外的内容

    2023-05-22 10:47:12
  • 重新编译PLSQL中的无效对象或者指定的对象 的方法

    2009-02-26 10:41:00
  • CSS控制字体效果的思考

    2011-06-14 09:44:02
  • 浅析数据完整性问题

    2007-10-07 12:44:00
  • mysql从执行.sql文件时处理换行的问题

    2009-09-06 11:46:00
  • IIRF(Ionic's Isapi Rewrite Filt er)入门,在IIS上重写Url

    2007-09-23 12:16:00
  • jQuery 1.4官方中文手册[译]

    2010-01-20 10:46:00
  • MYSQL5 下的兼容说明(my.ini my.conf)

    2008-02-23 10:13:00
  • YUI学习笔记(1)

    2009-01-12 18:06:00
  • 图片变形扭曲特效js脚本

    2008-11-20 12:57:00
  • asp之家 网络编程 m.aspxhome.com