罗斯文 - 一个托运人在一年内处理了多少个国家

时间:2018-04-25 08:27:21

标签: sql sql-server

我的运费查询需要一些帮助。 我需要指出,一家航运公司去年交付了多少个不同的国家。我当前的查询如下所示:

SELECT CompanyName, Count(o.CountryID) as Shipments, o.CountryID as Countries
FROM Shippers s
INNER JOIN Orders o ON s.ShipperID = o.ShipVia
WHERE DATEPART(year, o.OrderDate)=1997
GROUP BY CompanyName, o.CountryID
ORDER BY Shipments DESC;

它向我提供了公司列表,该公司向CountryID发货的国家/地区的次数。

United Package  26  9
United Package  26  20
Speedy Express  23  9
Speedy Express  19  20
United Package  17  4
Speedy Express  16  4

我需要的是计算一家航运公司交付的特殊国家数量。所以例如它应该给我:

United Package 120 4
Speedy Express 90  3

United Package向120个不同的国家/地区发送120个订单。 如何更改查询以获得该结果?

2 个答案:

答案 0 :(得分:1)

SELECT CompanyName, SUM(Shipments) AS Shipments,COUNT(DISTINCT Countries) AS Countries
FROM
(
SELECT CompanyName, Count(o.CountryID) as Shipments, o.CountryID as Countries
FROM Shippers s
INNER JOIN Orders o ON s.ShipperID = o.ShipVia
WHERE DATEPART(year, o.OrderDate)=1997
GROUP BY CompanyName, o.CountryID
) AS T
GROUP BY CompanyName
ORDER BY Shipments DESC

答案 1 :(得分:0)

我建议:

SELECT s.CompanyName, Count(*) as Shipments,
       COUNT(DISTINCT o.CountryID) as Countries
FROM Shippers s INNER JOIN
     Orders o
     ON s.ShipperID = o.ShipVia
WHERE o.OrderDate >= '1997-01-01' AND o.OrderDate < '1998-01-01'
GROUP BY s.CompanyName
ORDER BY Shipments DESC;

注意:

  • 限定所有列名称,尤其是在具有多个表引用的查询中。
  • 请勿使用datepart()。这阻止了索引的使用。相反,直接比较日期。
  • COUNT(DISTINCT)似乎可以做你想做的事。