易截截图软件、单文件、免安装、纯绿色、仅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获取每组前10%的数据

sqlserver2005有关键字ntile(x)和over(partition by.. order by..)子句配合.
比如获取每个表的前10%个字段。
select id , name , colid , rn from (
select * , rn = ntile (10 )
    over (partition by id order by colorder )
from syscolumns )t where rn = 1 ......

总结一点Access与Sqlserver的sql的差异

最近整理出来的.如果不完全的话希望大家补充.
在access中,转换为大写的sql函数是ucase,在sqlserver中,转换为大写的函数是upper;在access中,转换为小写的函数是lcase,在sqlserver中,转换为小写的函数是lower;在access中,取当前时间的函数是now,另外还有一个取日期函数date,在sqlserver中,取当前的函数是getdate ......

c#中高效的excel导入sqlserver的方法

本文来自CSDN博客:http://blog.csdn.net/jinjazz/archive/2008/07/14/2650506.aspx
将oledb读取的excel数据快速插入的sqlserver中,很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,最好的办法是使用bcp,也就是System.Data.SqlClient.SqlBulkCopy 类来实现。不但速度快,而且代码简单,下面测试代码导入一个6 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号