SqlServer如何用Sql语句自定义聚合函数

2024-12-17 05:23:33
推荐回答(5个)
回答1:

Sql Server自定义聚合函数详细步骤

开始->


输出->

首先用VS2008/VS2005建立一个SQL Server项目,右键解决方案添加新项

点击“确定”按钮后,SQL Server项目会要求连接一个数据库,我们可以选择一个数据库


然后在工程中加入一个聚合类(joinstr.cs),如图

joinstr.cs中的最终代码如下:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;
                             
                             
[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined, //use custom serialization to serialize the intermediate result
    IsInvariantToNulls = true, //optimizer property
    IsInvariantToDuplicates = false, //optimizer property
    IsInvariantToOrder = false, //optimizer property    
    MaxByteSize = 8000), //maximum size in bytes of persisted value
]
                             
                             
public struct JoinStr:IBinarySerialize
{
    private StringBuilder sbIntermediate;
    public void Init()
    {
       sbIntermediate = new StringBuilder();
    }
                             
    public void Accumulate(SqlString Value)
    {
                             
        if (Value == null || Value.ToString().ToLower().Equals("null"))
        {
            return;
        }
        else
        {
            sbIntermediate.Append(Value);
        }
    }
                             
    public void Merge(JionStr Group)
    {
        sbIntermediate.Append(Group.sbIntermediate);
    }
                             
    public SqlString Terminate()
    {
                                    
        return new SqlString(sbIntermediate.ToString());
    }
                             
    // This is a place-holder member field
                             
                             
    #region IBinarySerialize Members
                             
    public void Read(System.IO.BinaryReader r)
    {
        sbIntermediate = new StringBuilder(r.ReadString());
    }
                             
    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(this.sbIntermediate.ToString());    
    }
    #endregion
}

在编写完上述代码后,可以使用Visual Studio来部署(右向工程,在弹出菜单上选“部署”即可)。

在执行上面的SQL语句之前,需要将SQL Server2005的clr功能打开

现在可以使用joinstr来聚合字符串了。

select [t_code_role].[role_mc] as '角色',dbo.JoinStr([t_code_right].[right_mc]+',') as '权限' from [t_data_roleright],[t_code_right],[t_code_role] where [t_data_roleright].[role_bm]=[t_code_role].[role_bm] and [t_data_roleright].[right_bm]=[t_code_right].[right_bm] group by [t_code_role].[role_mc]

回答2:

有两个写法:   

select * from tblDept
where id in(select DeptID from tblSalary group by DeptID having  
count(case when Salary>3000 then 1 else null end)*1.0/count(*)>0.5)

select * from tblDept
where id in(select DeptID from tblSalary group by DeptID having  
sum(case when Salary>3000 then 1 else 0 end)*1.0/count(*)>0.5)

回答3:

我记得sql server 有function ,百度一下如何创建function。function与聚合函数是一回事。

回答4:

三楼回答的很好,标记一下,项目中要用到

回答5:

sql语句能实现吗?只知道sqlclr能实现