为select distinct添加where约束

时间:2013-08-10 12:51:39

标签: mysql sql

表概述:

2列

i_trans_to和i_trans_amnt

i_trans_to由ID组成,i_trans_amnt包含用户已存入帐户的金额

用户可能只存入这些金额300,175,75,40,20(因此i_trans_amnt列仅包含这些值)

IDS可能有多个条目,因为用户可以存放多次。

我想要一个选择

的查询

1.所有存款总额大于500的用户

2.对于所有这些用户,查询必须告知他所做的条目类型(例如:5个条目的Rs.300和2个条目的Rs.175)

我成功设计了查询,除了用户必须存放在rs.500上的约束 这是查询

    SELECT DISTINCT i_trans_to, 
                SUM( i_trans_amnt ),
                (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=300 AND transac.i_trans_to=current.i_trans_to) AS level1,
                 (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=175 AND transac.i_trans_to=current.i_trans_to) AS level2,
                 (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=75 AND transac.i_trans_to=current.i_trans_to) AS level3,
                 (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=40 AND transac.i_trans_to=current.i_trans_to) AS level4,
                 (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=40 AND transac.i_trans_to=current.i_trans_to) AS level5,
                 (SELECT COUNT(*) 
                 FROM transac 
                 WHERE i_trans_amnt=20 AND transac.i_trans_to=current.i_trans_to) AS level6
FROM transac as current
WHERE SUM( current.i_trans_amnt )>500
GROUP BY i_trans_to

我尝试在查询结尾处添加一个where子句,其中我写了SUM(i_trans_amnt)> 500,但这给了我一个错误。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

我更改了您的查询,您可以使用一组案例陈述获取level总计,这将加快您的查询速度。

可以在SUM( i_trans_amount)子句中查看

HAVING,有关此详细信息,请参阅Sylvain Leroux答案

SELECT 
    i_trans_to, 
    SUM( i_trans_amnt ),
    count(CASE WHEN i_trans_amnt=300 THEN 1 END ) AS level1,
    count(CASE WHEN i_trans_amnt=175 THEN 1 END ) AS level2,
    count(CASE WHEN i_trans_amnt=75 THEN 1 END ) AS level3           
FROM 
    transac as current
HAVING
    SUM( i_trans_amnt ) > 500
GROUP BY 
    i_trans_to

答案 1 :(得分:0)

我首先编写了一个查询,列出了所有存款金额超过500%的ID。然后我在连接中使用该查询只保留那些(所有其他ID都不会通过JOIN条件)。然后,我只需对两列进行分组,以便能够为每个ID显示每个金额的存款数量。

SELECT
  transac.i_trans_to,
  transac.i_trans_amnt,
  COUNT(0) AS number_of_times_amount_was_deposited
FROM
  transac
  JOIN (
    SELECT
      i_trans_to
    FROM
      transac
    GROUP BY
      i_trans_to
    HAVING
      SUM(i_trans_amnt) > 500
  ) AS large_depositors ON transac.i_trans_to = large_depositors.i_trans_to
GROUP BY
  i_trans_to,
  i_trans_amnt

答案 2 :(得分:0)

请参阅WHERE vs HAVING (请在该帖子上为此答案提供 Quassnoi

  

在GROUP BY之前应用WHERE,之后应用HAVING(并且可以过滤聚合)。

聚合函数是SUM()COUNT()以及适用于行组的所有函数:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html