如何在SQL中过滤数学计算的数据?

时间:2013-07-30 17:39:04

标签: sql logic arithmetic-expressions

这可能比我想象的要容易,但我很难过。我写了以下查询,该查询总结了客户在特定商店所做的所有购买,以及同一客户在同一商店的总回报,最后,存储了从总数中减去总回报的结果在名为TOTAL_SPENT的计算列中购买。这是我的疑问:

SELECT Account_Id,
  SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
  SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
  (TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
WHERE Store = 'Store XYZ'
GROUP BY Account_Id
ORDER BY TOTAL_SPENT DESC

我的问题是这个查询返回了数十万条记录,但我只关心大约10%的数据返回。所以,假设您只想看到TOTAL_SPENT> = 500.00返回的数据。但对于我的生活,我无法弄清楚如何做到这一点! 垂头丧气

1 个答案:

答案 0 :(得分:1)

在SQL中,WHERE子句在 SELECT子句之前处理。因此,当SQL开始过滤您的表中与您的查询相关的行时,它尚未知道TOTAL_SPENT

有几种方法可以解决这个问题。

1)重复WHERE子句中的表达式,而不是引用SELECT子句中的列名:

SELECT Account_Id,
  SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
  SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
  (TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
WHERE Store = 'Store XYZ'
GROUP BY Account_Id
ORDER BY 
  (SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) - SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END)) DESC

注意:如果您要查找<{1>}超过500的群组,请使用TOTAL_SPENT子句代替{{1 }}

2)使用视图。删除HAVING子句并使用您的查询创建WHERE。然后,从视图中选择并添加WHERE子句。

VIEW

3)使用嵌套的SELECT:

WHERE

4)如果您的数据库支持它,请使用CTE:

CREATE VIEW Whatever AS
   SELECT Account_Id,
      SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS    TOTAL_PURCHASED,
      SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
      (TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
   FROM Transactions_Table
   GROUP BY Account_Id;

SELECT * From Whatever WHERE TOTAL_SPENT >= 500