1

这给了我一个使用外部资金的用户列表。

SELECT
  table_user.user as user,
  sum(table_deposit.amount) as TotalExternalDeposits,payby,pro_id
FROM table_deposit inner join table_user on table_deposit.user = table_user.user 
WHERE  table_deposit.pro_id <>  'Cash A/C'
AND  table_deposit.batch NOT LIKE  '%adj%'
AND table_deposit.batch NOT LIKE  'Xmas%'
AND table_deposit.batch NOT LIKE  'X-mas%'
group by table_user.user
order by table_user.user

我的问题是现在我需要一份未使用外部资金的用户列表 ( TotalExternalDeposits = 0)。我迷路了。

当我尝试添加类似以下内容时:HAVING TotalExternalDeposits = 0我得到一个空集。我知道有成千上万的用户没有使用外部资金。

4

4 回答 4

2

假设join没有过滤掉您正在寻找的任何用户,您可以使用not

SELECT table_user.user as user, sum(table_deposit.amount) as TotalExternalDeposits,payby,pro_id
FROM table_deposit inner join
     table_user
    on table_deposit.user = table_user.user 
WHERE not (`table_deposit`.pro_id <>  'Cash A/C' AND 
           `table_deposit`.batch NOT LIKE  '%adj%' AND
           table_deposit.batch NOT LIKE  'Xmas%' AND
           table_deposit.batch NOT LIKE  'X-mas%'
          )
group by `table_user`.user
order by `table_user`.user

但是,这会获得拥有非“外部资金”帐户的用户。也就是说,上面得到的用户至少有一个非外部资金账户。您可能希望确保没有帐户是外部资金(而不是任何帐户)。在这种情况下,您希望将条件移动到一个having子句,您可以在其中计算匹配的行数——并确保值为 0:

SELECT tu.user as user, sum(td.amount) as TotalExternalDeposits, payby, pro_id
FROM table_user tu left outer join
     table_deposit td
     on td.user = tu.user 
group by tu.user
having sum((td.pro_id <>  'Cash A/C' AND 
            td.batch NOT LIKE  '%adj%' AND
            td.batch NOT LIKE  'Xmas%' AND
            td.batch NOT LIKE  'X-mas%'
           ) or td.user is null
          ) = 0
order by tu.user;

我还为表使用了表别名。我认为这使阅读更容易。

于 2013-07-27T22:21:34.383 回答
0

由于 HAVING 子句不起作用,听起来那些没有使用外部资金的用户在 table_deposit 中没有行。如果是这种情况,您的查询应该类似于:

SELECT
  table_user.user as user,
  0 as TotalExternalDeposits,
  payby,
  pro_id
FROM table_user 
WHERE user NOT IN (
  SELECT user
  FROM table_deposit
)
于 2013-07-27T23:06:15.350 回答
0

我想这HAVING可以解决问题,但可能是您失败了,因为您似乎忘记在子句中添加paybyand或者可能是因为您尝试使用别名。pro_idGROUP BY

 SELECT
   table_user.user as user,
   sum(table_deposit.amount) as TotalExternalDeposits,payby,table_deposit.pro_id
 FROM table_deposit inner join table_user on table_deposit.user = table_user.user 
 WHERE  table_deposit.pro_id <>  'Cash A/C'
 AND  table_deposit.batch NOT LIKE  '%adj%'
 AND table_deposit.batch NOT LIKE  'Xmas%'
 AND table_deposit.batch NOT LIKE  'X-mas%'
 GROUP BY table_user.user,payby,table_deposit.pro_id
 HAVING sum(table_deposit.amount) = 0
 ORDER BY table_user.user
于 2013-07-28T03:49:38.833 回答
0

如果它是一个或者你只需​​要相反的一组查询,只需颠倒条件:

SELECT
  table_user.user as user,
  sum(table_deposit.amount) as TotalExternalDeposits,payby,pro_id
FROM table_deposit inner join table_user on table_deposit.user = table_user.user 
WHERE  table_deposit.pro_id =  'Cash A/C'
OR  table_deposit.batch  LIKE  '%adj%'
OR table_deposit.batch  LIKE  'Xmas%'
OR table_deposit.batch  LIKE  'X-mas%'
group by table_user.user
order by table_user.user
于 2013-07-28T02:15:38.407 回答