2009-10-22 73 views
1

我无法让我的用户定义的函数正常运行。我在SQL Server 2000上运行。SQL用户定义函数问题

我试图返回一个表中的所有用户在“BillingTransactions”表中有一个平衡。我们的交易由RecordType字段指定; 0购买,1付款。所以我想要做的是获得所有用户的列表,其中RecordType 0的每个事务的总和等于每个事务与RecordType 1的总和。这就是我的函数的内部部分现在的样子:

SELECT DISTINCT UserName FROM BillingTransactions 
WHERE (SELECT SUM(AMOUNT) 
    FROM BillingTransactions 
    WHERE [BillingTransactions].[RecordType]= 0 
    AND 
    [BillingTransactions].[UserName]= UserName) 
    = 
    (SELECT SUM(AMOUNT) 
    FROM BillingTransactions 
    WHERE [BillingTransactions].[RecordType]= 1 
    AND 
    [BillingTransactions].[UserName]= UserName) 

我有一种感觉,这不是最有效的方式来做到这一点...有没有其他方式可以看到如何去做这件事?谢谢!

+0

为什么不将此存储过程? – 2009-10-22 22:09:11

回答

11

与任何SQL查询,效率会被你的数据的实际布局(表结构,索引结构)一样多的文本来驱动查询。以下是表达相同请求的相同查询的一个版本,但逐字逐句并可能更有效:

SELECT UserName 
FROM BillingTransactions 
GROUP BY UserName 
HAVING 0 = SUM(
    CASE RecordType 
    WHEN 1 THEN AMOUNT 
    WHEN 0 THEN -AMOUNT 
    ELSE 0 
    END); 
+0

这真的很酷。 – Manu 2009-10-22 22:10:27

+0

非常酷,谢谢! – Kevin 2009-10-22 22:13:26

+0

非常优雅的解决方案。 – 2009-10-22 22:13:57

3

尝试这样代替:

select a.username 
from (select username, sum(amount) totalAmount 
    from BillingTransactions 
    where RecordType = 0 
    group by username 
    ) a 
join (select username, sum(amount) totalAmount 
    from BillingTransactions 
    where RecordType = 1 
    group by username 
    ) b on b.username = a.username and b.totalAmount = a.totalAmount