将WHERE CLAUSE与GROUP BY一起使用

时间:2015-12-29 09:06:12

标签: mysql group-by having where-in

我想使用2个表格显示每张帐单的销售商品总价值 -

这是表项,表的结构是I_Code-> int,Name-> Varchar,Category-> Varchar,Rate-> int enter image description here

这是表格账单,表格的结构是BillNo-> int,Date-> date, I_Code-> int,qty-> int

enter image description here

以下是我想要获得所需输出的查询

SELECT i.`rate` * b.`qty`, b.`BillNo` FROM bills b, items i WHERE b.I_Code=i.I_Code GROUP BY `BillNo` ;

但输出不正确 enter image description here

预期输出 enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT SUM(A.TOT), b.`BillNo`
FROM (
    SELECT i.`rate` * b.`qty` AS TOT, b.`BillNo`
    FROM bills b, items i
    WHERE b.I_Code = i.I_Code
) AS A
GROUP BY `BillNo`;

SELECT SUM(i.`rate` * b.`qty`) AS TOT, b.`BillNo`
FROM bills b, items i
WHERE b.I_Code = i.I_Code
GROUP BY `BillNo`;