【发布时间】:2018-04-09 20:20:04
【问题描述】:
我有点怀疑,我正在使用Northwind 数据库做一些练习。我正在尝试获得一份按年份显示出货量的报告,以及每个航运公司的出货总数。它还需要显示该公司完成的发货百分比,然后需要显示哪家公司发货最多(“X”表示发货最多的公司,“-”表示其余发货),例如代码的注释部分:
IF (Perc > 36, "X", "-")
我已经有了部分代码,我只是在努力处理最后一部分。
这是我所拥有的:
SELECT
/* First we get the years. */
DISTINCT YEAR(P.OrderDate) AS 'ShipYear',
/* Now we get the names of the different shipping agencies. */
(SELECT Shippers.CompanyName
FROM dbo.Shippers
WHERE Shippers.ShipperID = P.ShipVia) AS 'Shipper',
/* The next step is counting the total of shipments *
* of that year with that company. */
(SELECT COUNT(C.ShipVia)
FROM dbo.Orders AS C
WHERE YEAR(C.OrderDate) = YEAR(P.OrderDate)
AND C.ShipVia = P.ShipVia) AS 'Shipments',
/* Now we get it's percentage. */
(SELECT (COUNT(C.ShipVia) * 100 /
(SELECT COUNT(*)
FROM dbo.Orders AS CC
WHERE YEAR(CC.OrderDate) = YEAR(P.OrderDate)))
FROM dbo.Orders AS C
WHERE YEAR(C.OrderDate) = YEAR(P.OrderDate)
AND C.ShipVia = P.ShipVia) AS 'Perc'
--IF (Perc > 36, "X", "-")
FROM
[dbo].[Orders] AS P
WHERE
P.OrderDate IS NOT NULL
ORDER BY
YEAR(P.OrderDate)
GO
这是报告的截图:
非常感谢您的帮助!
【问题讨论】:
标签: sql max percentage northwind