SQL错误消息8120修复

时间:2017-10-02 00:48:31

标签: sql sql-server group-by

我有一些麻烦,弄清楚我的错误在哪里。这是个问题:

Write a SELECT statement that returns the following columns
a. ShipmentOrderDate
b. Clients Email Address
c. Column that calculates the Total Order called OrderTotal
d. A Column that uses the Rank() function to return a column named OrderTotalRank that
ranks the Order Total in Desc Order.
e. A column that uses the DenseRank() function to return a column called DenseRank that
ranks the Order Total in Desc Order.

这就是我编码的内容:

SELECT ShipmentOrderDate, EmailAddress,
    SUM(sh.ShipItemPrice * sh.Quantity) AS OrderTotalRank,
    RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS OrderTotalRank,
    DENSE_RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS DenseRank
FROM Clients AS c JOIN Shipments AS s 
    ON c.ClientID = s.ClientID
    JOIN ShipItems AS sh
    ON s.ShipmentID = sh.ShipmentID

当我运行代码时,我收到此错误:

  

Column' Shipments.ShipmentOrderDate'在选择列表中无效   因为它不包含在聚合函数或   GROUP BY子句。

1 个答案:

答案 0 :(得分:1)

您需要GROUP BY,因为SELECT中有汇总功能。它们与您正在使用的窗口函数分开:

SELECT ShipmentOrderDate, EmailAddress,
       SUM(sh.ShipItemPrice * sh.Quantity) AS OrderTotalRank,
       RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS OrderTotalRank,
       DENSE_RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS DenseRank
FROM Clients c JOIN
     Shipments s 
     ON c.ClientID = s.ClientID JOIN
     ShipItems sh
     ON s.ShipmentID = sh.ShipmentID
GROUP BY ShipmentOrderDate, EmailAddress;