【问题标题】:SQL User Defined Function questionSQL 用户定义函数问题
【发布时间】:2012-05-09 20:46:06
【问题描述】:

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

我正在尝试返回在“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)

我觉得这不是最有效的方法......您还有其他方法可以解决这个问题吗?谢谢!

【问题讨论】:

  • 为什么不把它变成一个存储过程呢?

标签: sql user-defined-functions


【解决方案1】:

与任何 SQL 查询一样,效率将取决于数据的实际布局(表结构、索引结构)与查询文本一样多。以下是表达相同请求的同一查询的一个版本,但逐字记录更少,可能更有效:

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

【讨论】:

    【解决方案2】:

    试试这样的:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多