创建视图并选择Top10

时间:2013-08-18 16:18:59

标签: sql-server

所以标题非常准确我想我差不多就在这里就是我拥有的东西

编辑:视图应该选择列vendorname,列LastInvoice,它是列中的最新日期和invoiceTotal列的总和。我希望这只显示前10名付费invoiceTotals以及相应的最新发票日期和供应商名称。

CREATE VIEW TOP10PAIDInvoices
AS
  SELECT VendorName,
         MAX(InvoiceDate)  AS LastInvoice,
         SUM(InvoiceTotal) AS SumOfInvoices
  FROM   Vendors
         JOIN Invoices
           ON Vendors.VendorID = Invoices.VendorID
  WHERE  (SELECT TOP 10 SumOfInvoices
          FROM   TOP10PAIDInvoices
          GROUP  BY SumOfInvoices
          HAVING SumOfInvoices > 0)
  ORDER  BY SumOfInvoices 

1 个答案:

答案 0 :(得分:1)

您的语法不正确,部分原因是您的视图def正在尝试自我引用。

当与TOP N表达式结合使用时,

ORDER BY在视图def中是合法的。

CREATE VIEW TOP10PAIDInvoices AS
SELECT TOP 10 VendorName = MAX(VendorName), MAX(InvoiceDate) AS LastInvoice, SUM(InvoiceTotal) AS SumOfInvoices
FROM Vendors JOIN Invoices
ON Vendors.VendorID = Invoices.VendorID
GROUP BY Vendors.VendorID
HAVING SUM(InvoiceTotal) > 0
ORDER BY SUM(InvoiceTotal) DESC;
GO