介意麻木SQL疯狂

时间:2014-12-24 06:30:15

标签: mysql sql select group-by having

此查询在invoices表格上运行,以帮助我决定我需要支付的费用

这是基表:

用户

+---------+--------+
| user_id |  name  |
+---------+--------+
|       1 | Peter  |
|       2 | Lois   |
|       3 | Stewie |
+---------+--------+

发票表:

+------------+---------+----------+--------+---------------+---------+
| invoice_id | user_id | currency | amount |  description  | is_paid |
+------------+---------+----------+--------+---------------+---------+
|          1 |       1 | usd      |    140 | Cow hoof      |       0 |
|          2 |       1 | usd      |     45 | Cow tail      |       0 |
|          3 |       1 | gbp      |      1 | Cow nostril   |       0 |
|          4 |       2 | gbp      |   1500 | Cow nose hair |       0 |
|          5 |       2 | cad      |      1 | eyelash       |       1 |
+------------+---------+----------+--------+---------------+---------+

我想要一个看起来像这样的结果表:

+---------+-------+----------+-------------+
| user_id | name  | currency | SUM(amount) |
+---------+-------+----------+-------------+
|       1 | Peter | usd      |         185 |
|       2 | Lois  | gbp      |        1500 |
+---------+-------+----------+-------------+

条件是:

  • 仅考虑尚未支付的发票,因此is_paid = 0
  • user_id <{1}}
  • 对它们进行分组
  • 如果user_id,货币对的currency因此不打算显示结果,因为我们不会支付低于100美元的发票(或相当于基于固定交换的发票)率)。

这是我到目前为止所做的事情(不工作 - 我猜是因为我按照GROUP&#39; ed参数进行过滤):

SUM(amount) < $100

帮助?

3 个答案:

答案 0 :(得分:4)

您无法在SUM中使用WHERE。请改用HAVING

答案 1 :(得分:1)

WHERE 条件

中使用 HAVING 子句代替 SUM

试试这个:

SELECT u.user_id, u.name, i.currency, SUM(i.amount) invoiceAmount 
FROM mydb.users u 
INNER JOIN mydb.invoices i ON u.user_id = i.user_id 
WHERE i.is_paid = 0
GROUP BY u.user_id, i.currency
HAVING SUM(i.amount) >= (CASE i.currency WHEN 'usd' THEN 100 WHEN 'gbp' THEN 155 WHEN 'cad' THEN 117 END)
ORDER BY u.name, i.currency;

答案 2 :(得分:1)

尝试这样的事情:

SELECT 
user_id, name, currency, sum(amount) due
FROM
invoice i
JOIN users u ON i.user_id=u.user_id
WHERE
is_paid = 0 AND
GROUP BY user_id, currency
having due >= 100
你存储汇率吗?将金额乘以金额以获得相对于基础货币的实际金额。

sum(amount*ex_rate) due