mysql查询行的总和,每行具有唯一的id

时间:2014-03-27 04:21:42

标签: mysql join subquery

我是mysql的新手。我收到candy_id并订购#作为输入(由*表示)。我想要一个可以添加巧克力和摩卡量的输出。我使用聚合尝试了很多查询,但是我无法得到结果。我还没试过JOIN。请帮忙。

进程:整个过程是...我将查询另一个表以获得一堆candy_id。订单#是固定数字(6)。然后我在此表中使用这两个来获取糖果类型及其各自的累积数量。对困惑感到抱歉。我很难提出这个问题

So the output will be

 candy_type    Total qty
  Chocolate     14
  Mocha         25



The database table is
    candy_id    candy_type    order#      qty
        1*        Chocolate     6*         12
        2         Vanilla       1          10
        3*        Mocha         6*         20
        4*        Chocolate     6*        2
        5         Orange        1          10
        6*        Mocha         6*         5
        7         Chocolate     6         13
        8         Chocolate     6          7

如何使用查询将abpve表减少到下面并进行聚合查询?有没有办法做背靠背查询

   candy_id    candy_type    order#      qty
        1*        Chocolate     6*         12
        3*        Mocha         6*         20
        4*        Chocolate     6*         2
        6*        Mocha         6*         5

2 个答案:

答案 0 :(得分:0)

应该很简单,我想

SELECT candy_type, SUM(qty) AS total_qty
FROM table
GROUP BY candy_type
WHERE order_id IN (6, 12)
AND candy_id IN (
  SELECT id
  FROM candy
  WHERE vendor = "foo"
  AND location = "bar"
)
ORDER BY candy_name ASC;

您也可以使用JOIN

执行此操作
SELECT
  table.candy_type,
  SUM(table.qty) AS total_qty

FROM table

JOIN candy
  ON candy.id       = table.candy_id
 AND candy.vendor   = "foo"
 AND candy.location = "bar"


GROUP BY table.candy_type
WHERE table.order_id IN (6, 12)
ORDER BY table.candy_name ASC;

答案 1 :(得分:0)

select candy_type, sum(qty) from
your table
where order# = order_number in your parameter
and candy_id in (your candy_id parameter)
group by candy_type