这是我的sql查询,用于获取下表:
select c.name, s.company, p.qty, p.qty * p.price as Total
from client c, purchase p, stock s
where c.clno = p.clno AND s.company = p.company
group by c.name, s.company, p.qty, p.qty * p.price
order by sum(p.qty) desc
上述查询的输出如下:
Name | Company | Qty | Total
John ABC 12 100
Bob XYZ 10 150
John ABC 5 50
Bob XYZ 20 250
Bob XYZ 2 20
Nav QRS 10 150
John ABC 10 150
我想要查询以获取如下输出:
Name | Company | Qty | Total
John ABC 27 300
Bob XYZ 32 420
Nav QRS 10 150
答案 0 :(得分:1)
到目前为止,您的查询使用GROUP BY
,但实际上并未聚合数据。您想要GROUP BY
的名称和公司,以及SUM
的数量和金额,例如:
select c.name, s.company, SUM(p.qty), SUM(p.qty * p.price) as Total
from client c
inner join purchase p on c.clno = p.clno
inner join stock s on s.company = p.company
group by c.name, s.company
order by Total desc
有关您的查询的其他评论:
ORDER BY
子句中使用列别名(此处为Total
;这可以使查询更易于阅读