SQL Server:标记表

时间:2018-04-09 20:20:04

标签: sql max percentage northwind

我有点怀疑,我正在使用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

以下是报告的截图:

Table report

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您正在使用OVER子句寻找窗口函数。

您没有指定您正在使用的数据库,因此我链接到上面的Microsoft SQL Server。

由于Perc列是一个子查询,您应该将SELECT语句包装成另一个,如下所示:

SELECT 'ShipYear', 'Shipper', 'Shipments', 'Perc'
     , MAX('Perc') OVER (PARTITION BY 'ShipYear') AS `MaxPerc`
  FROM ( // your query goes here
       ) x

这将告诉你它是如何工作的。由于您需要X-,因此请执行以下操作:

SELECT 'ShipYear', 'Shipper', 'Shipments', 'Perc'
     , CASE WHEN 'Perc' = MAX('Perc') OVER (PARTITION BY 'ShipYear')
            THEN 'X'
            ELSE '-'
       END AS 'Best'
  FROM ( // your query goes here
       ) x