SQL LIMIT 1 DESC命令

时间:2014-04-24 02:40:57

标签: sql sql-server ssms

我试图只显示每个工作中心最畅销的产品,但是,它一直告诉我LIMIT 1是不正确的语法。我似乎无法在这里找到答案,所以我决定提问。这是我的疑问。

SELECT WorkCenter.WorkCenterCode, Product.Name, SUM(CustomerOrderLine.Quantity*CustomerOrderLine.ActualPrice) AS 'Total Sales'
FROM WorkCenter 
    INNER JOIN Product ON WorkCenter.WorkCenterCode = Product.WorkCenterCode 
    INNER JOIN CustomerOrderLine ON Product.ProductID = CustomerOrderLine.ProductID
    GROUP BY WorkCenter.WorkCenterCode, Product.Name
    ORDER BY 'Total Sales' DESC 
    LIMIT 1

3 个答案:

答案 0 :(得分:1)

以下是您的查询清理了一下:

SELECT  wc.WorkCenterCode, p.Name, SUM(col.Quantity*col.ActualPrice) AS "Total Sales"
FROM WorkCenter wc INNER JOIN
     Product p
     ON wc.WorkCenterCode = p.WorkCenterCode INNER JOIN
     CustomerOrderLine col
     ON p.ProductID = col.ProductID
GROUP BY wc.WorkCenterCode, p.Name
ORDER BY "Total Sales" DESC
LIMIT 1

请注意从双引号到单引号的重要更改。这对于order by子句尤其重要,因此该子句实际上做了一些事情,而不是按常量排序。添加表别名使查询更容易阅读。

如果您使用的是Visual Studio,则应使用top而不是limit

SELECT TOP 1 wc.WorkCenterCode, p.Name, SUM(col.Quantity*col.ActualPrice) AS "Total Sales"
FROM WorkCenter wc INNER JOIN
     Product p
     ON wc.WorkCenterCode = p.WorkCenterCode INNER JOIN
     CustomerOrderLine col
     ON p.ProductID = col.ProductID
GROUP BY wc.WorkCenterCode, p.Name
ORDER BY "Total Sales" DESC;

编辑:

对于每个工作中心一行,将其用作row_number()的子查询:

SELECT WorkCenterCode, Name, "Total Sales"
FROM (SELECT wc.WorkCenterCode, p.Name, SUM(col.Quantity*col.ActualPrice) AS "Total Sales",
             row_number() over (partition by wc.WorkCenterCode order by SUM(col.Quantity*col.ActualPrice) desc) as seqnum
      FROM WorkCenter wc INNER JOIN
           Product p
           ON wc.WorkCenterCode = p.WorkCenterCode INNER JOIN
           CustomerOrderLine col
           ON p.ProductID = col.ProductID
      GROUP BY wc.WorkCenterCode, p.Name
     ) t
WHERE seqnum = 1
ORDER BY "Total Sales" DESC;

答案 1 :(得分:0)

对于SQL Server,请使用SELECT TOP 1

SELECT TOP 1 WorkCenter.WorkCenterCode, Product.Name, SUM(CustomerOrderLine.Quantity*CustomerOrderLine.ActualPrice) AS [Total Sales]
FROM            WorkCenter INNER JOIN
                     Product ON WorkCenter.WorkCenterCode = Product.WorkCenterCode INNER     JOIN
                     CustomerOrderLine ON Product.ProductID = CustomerOrderLine.ProductID
GROUP BY WorkCenter.WorkCenterCode, Product.Name
ORDER BY [Total Sales] DESC 

答案 2 :(得分:0)

这是关于使用ROW_NUMBER()主题的另一个SO questionTOP 1只会返回一行,而ROW_NUMER()可以每组返回一行。