如何避免分组中出现重复值?

时间:2019-07-13 20:39:39

标签: sql sql-server tsql

我想指出每个公司的下单总额(金额)。

PS: 总金额=数量*单价

select  Customers.CompanyName, ([Order Details].OrderID), sum([Order Details].Quantity*[Order Details].UnitPrice)
from Customers
 join orders
on customers.CustomerID=customers.CustomerID
 join [Order Details]
on orders.OrderID=[Order Details].OrderID
group by Customers.CompanyName, [Order Details].OrderID
order by customers.CompanyName asc

上面的代码根据OrderID列出行,并复制CompanyName

另一方面,下面的代码并没有重复CompanyName,但是它显示了[Order Details]中所有订单的总金额

select  Customers.CompanyName, sum([Order Details].Quantity*[Order Details].UnitPrice)
from Customers
 join orders
on customers.CustomerID=customers.CustomerID
 join [Order Details]
on orders.OrderID=[Order Details].OrderID
group by Customers.CompanyName
order by customers.CompanyName asc

我的第二个查询执行此操作

Alfreds Futterkiste 10643   1086,00
Alfreds Futterkiste 10692   878,00
Alfreds Futterkiste 10702   330,00
Alfreds Futterkiste 10835   851,00
Alfreds Futterkiste 10952   491,20
Alfreds Futterkiste 11011   960,00
Ana Trujillo Emparedados y helados  10308   88,80
Ana Trujillo Emparedados y helados  10625   479,75
Ana Trujillo Emparedados y helados  10759   320,00
Ana Trujillo Emparedados y helados  10926   514,40

但是我想要这个:

Alfreds Futterkiste 3636,00
Ana Trujillo Emparedados y helados 1402,95

1 个答案:

答案 0 :(得分:1)

我认为您只需要一个聚合查询:

select c.CompanyName,
       sum(od.Quantity * od.UnitPrice) as totalamount
from Customers c join
     orders o
     on c.CustomerID = o.CustomerID join
     [Order Details] od
     on o.OrderID = od.OrderID
group by c.CompanyName
order by c.CompanyName asc;

如果您要在结果集中的每个CompanyName行,那么该行应该是GROUP BY中的唯一列。

还请注意表别名的使用。这些使查询更易于编写和阅读。