易截截图软件、单文件、免安装、纯绿色、仅160KB

SQLServer任意列之间的聚合

SQLServer任意列之间的聚合 收藏
sql的max之类的聚合函数只能针对同一列的n行运算,如果对n列运算,一般都用case 语句来判断,如果列少还比较容易写,列多了就麻烦了。这里介绍一个通过xml合并列并转为行集后直接用聚合函数求值的方法,测试用例和代码如下
--------------------------------------------------------------------------------
/*
测试名称:利用 XML 求任意列之间的聚合
测试功能:对一张表的列数据做 min 、 max 、 sum 和 avg 运算
运行原理:字段合并为 xml 后做 xquery 查询转为行集后聚合
作者: jinjazz (近身剪)
*/
-- 建立测试环境
declare @t table (
id smallint ,
a smallint , b smallint ,
c smallint , d smallint ,
e smallint , f smallint )
 
insert into @t
select 1, 1, 2, 3, 4, 6, 7 union all
select 2, 34, 45, 56, 54, 9, 6
 
-- 测试语句
select   a.*, c.*
from @t a outer apply(
select doc=(
select * from @t as doc where id= a. id  for xml path ( '' ), type   )
) b
outer apply(
select
min ( r) as minValue,
max ( r) as maxValue,
sum ( r) as sumValue,
avg ( r) as avgValue
  from (
    select cast ( cast ( d. n. query( 'text()' ) as varchar ( max )) as int ) as r
       from doc. nodes( '/a,b,c,d,e,f' ) D( n)) tt
) c
     
/* 测试结果
 
id     a      b      c      d      e      f      minValue    maxValue    sumValue    avgValue
------ ------ ------ ------ ------ ------ ------ ----------- ----------- ----------- -----------
1      1      2      3      4      6      7      1       


相关文档:

Sqlserver得到汉字拼音首字母存储过程

Sqlserver得到汉字拼音首字母存储过程:
create function [dbo].[fun_getPY]
(
@str nvarchar(4000)
)
returns nvarchar(4000)
as
begin
declare @word nchar(1),@PY nvarchar(4000)
set @PY=''
while len(@str)>0
begin
   set @word=left(@str,1)
   --如果非汉字字符,返回原字符
& ......

SQLServer批量倒入目录文件 收藏


可以用扩展存储过程xp_dirtree获取文件列表,用openrowset倒入数据到二进制字段。
openrowset的用法可以参考msdn
http://technet.microsoft.com/zh-cn/library/ms190312.aspx
如果文件很多,建议还是用程序倒入了
if (object_id ('t_bulkResult' ) is   not   null )
drop table t_bulkResult ......

SQLServer获取Excel中所有Sheet

E盘根目录新建一个Excel文件aa.xls后测试如下代码
use tempdb
go
if (object_id ('udf_getExcelTableNames' ) is not null )
    drop function dbo .udf_getExcelTableNames
go
create function udf_getExcelTableNames (@filename varchar (1000 ))
returns @t table (id int , name varchar ( ......

SQLServer系统存储过程

sp_databases --列出服务器上的所有数据库
sp_server_info --列出服务器信息,如字符集,版本和排列顺序
sp_stored_procedures--列出当前环境中的所有存储过程
sp_tables --列出当前环境中所有可以查询的对象
sp_start_job --立即启动自动化任务
sp_stop_job --停止正在执行的自动化任务
sp_password --添加或� ......

SQLServer中的循环批处理

  SQLServer中的循环批处理
GO命令后面加一个常量就可以了
下面方法可以用来快速生成一批数据
if (object_id ('t' ) is not null ) drop table t
go
create table t (id int identity (1 , 1 ), name varchar (40 ))
go
insert into t (name ) select newid ()
go 10
select * from t
/*
1 &nbs ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号