找到第n个最高

时间:2019-02-12 22:56:26

标签: sql sql-server

SELECT  CONCAT(C.CUSTOMER_FNAME, ' ',C.CUSTOMER_LNAME) AS FullNAME, SUM(QTY* PRICE)AS TOTAL_SPENDINGS

    FROM (SELECT DISTINCT TOP 2 TOTAL_SPENDINGS) RESULT

          Customers$ C INNER JOIN Invoices$ Inv ON C.CUSTOMER_ID=Inv.CUSTOMER_ID
          INNER JOIN InvDetails$ InvD ON Inv.INVOICE_ID=InvD.INVOICE_ID
          INNER JOIN Products$ P ON P.PRODUCT_ID=InvD.PRODUCT_ID

    GROUP BY  C.CUSTOMER_FNAME,C.CUSTOMER_LNAME
    ORDER BY TOTAL_SPENDINGS DESC

我正在尝试向支出最高的k位客户介绍这是我到目前为止所做的,但是我得到了

  

“ Customers $”附近的语法不正确。

1 个答案:

答案 0 :(得分:1)

您缺少计算表RESULT和Customer表之间的联接条件:

SELECT  CONCAT(C.CUSTOMER_FNAME, ' ',C.CUSTOMER_LNAME) AS FullNAME, SUM(QTY* PRICE)AS TOTAL_SPENDINGS

FROM (SELECT DISTINCT TOP 2 TOTAL_SPENDINGS) RESULT
      <missing INNER / LEFT join here>
      Customers$ C <missing ON here>  INNER JOIN Invoices$ Inv ON C.CUSTOMER_ID=Inv.CUSTOMER_ID
      INNER JOIN InvDetails$ InvD ON Inv.INVOICE_ID=InvD.INVOICE_ID
      INNER JOIN Products$ P ON P.PRODUCT_ID=InvD.PRODUCT_ID

GROUP BY  C.CUSTOMER_FNAME,C.CUSTOMER_LNAME
ORDER BY TOTAL_SPENDINGS DESC