请,我需要您的帮助,我是这个主题的新手,所以我有2个拖曳表Order表和Order Detail表。我想对订单表中的订单金额求和,并按订单明细表中存在的产品ID进行分组。我正在重复行。
select p.productName
SUM(o.Amount - o.discount) as OrdersTotal
FROM dbo.order o
inner join
OrderDetail d
ON o.orderid = d.orderid
inner join
dbo.product p
ON d.productid = p.productid
where o.orderdate >= @fromdate
and o.orderdate <= @todate
group by p.productname, o.discount
我得到的结果如下
product name orders total
------------ ------------
product A 150
product A 20
product B 45
product B 13
所以,请问如何解决这个问题?谢谢
答案 0 :(得分:1)
您应该仅按产品名称分组,以便所有具有相同产品名称的记录都包括在金额的总和中:
select p.productName
SUM(o.Amount) as OrdersTotal
FROM dbo.order o
inner join
OrderDetail d
ON o.orderid = d.orderid
inner join
dbo.product p
ON d.productid = p.productid
where o.orderdate >= @fromdate
and o.orderdate <= @todate
group by p.productname