日期:2014-05-16 浏览次数:20526 次
select o.OrderID,SUM(Num*UnitPrice)-SUM(t.Amount)--(如果这样写了,因为会关联出笛卡尔积,所以不能直接用SUM....)
from Orders o
join OrderDetail od on od.OrderID=o.OrderID
join Transaction t on t.OrderID=o.OrderID
group by o.OrderID
with t1 as (
select o.OrderID,SUM(Num*UnitPrice) Amount
from Orders o
join OrderDetail od on od.OrderID=o.OrderID
group by o.OrderID
),t2 as (
select o.OrderID,SUM(t.Amount) Amount
from Orders o
join Transaction t on t.OrderID=o.OrderID
group by o.OrderID
)
select t1.OrderID,t1.Amount-t2.Amount from t1 join t2 on t1.OrderID=t2.OrderID
这是我自己写的 CLR开发的一个聚合函数。(配合 Distinct关键字用的求和函数)
用法:第一个参数,求和字段;第二个参数,按哪个字段去重复。不好理解可以看看最后的用法。
虽然写法上简单了。但性能上很差。希望MSSQL在下个版本,提供类似的内置聚合函数吧。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;
using System.Collections;
[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined,
IsInvariantToNulls = true,
IsInvariantToDuplicates = false,
IsInvariantToOrder = false,
MaxByteSize = 8000)
]
public struct SumDistinctString : IBinarySerialize
{
private decimal sum;
public void Init()
{
sum = 0m;
}
public void Accumulate(SqlDecimal Value, SqlString DistinctField)
{
&