查询顶级客户的SQL查询

时间:2015-03-12 19:40:01

标签: sql sql-server view

我想看看前10位客户,这是我到目前为止所做的,我做错了什么?

CREATE VIEW vwTopCustomer
AS 
   SELECT TOP 10 * 
       (CustomerID) AS TotalMoneySpent, 
       SUM(Quantity*Price)
   FROM 
       tblCUSTOMER c
   JOIN 
       tblORDER o ON c.CustomerID = o.CustomerID
   JOIN 
       tblORDER_PRODUCT op ON o.OrderID = op.OrderID
   JOIN 
       tblPRODUCT p ON op.ProductID = p.ProductID
   GROUP BY  
       CustomerID
   ORDER BY 
       TotalMoneySpent DESC
   GO

3 个答案:

答案 0 :(得分:1)

您不能group by一列,然后在查询结果中Select *

试试这个编辑过的版本..

CREATE VIEW vwTopCustomer
AS 
   SELECT TOP 10 
       (CustomerID), 
       SUM(Quantity*Price) AS TotalMoneySpent
   FROM 
       tblCUSTOMER c
   JOIN 
       tblORDER o ON c.CustomerID = o.CustomerID
   JOIN 
       tblORDER_PRODUCT op ON o.OrderID = op.OrderID
   JOIN 
       tblPRODUCT p ON op.ProductID = p.ProductID
   GROUP BY  
       CustomerID
   ORDER BY 
       2 DESC
   GO

答案 1 :(得分:1)

在没有看到数据的情况下,我无法确定,但我注意到的两件事是你选择了前10个*然后是两个字段。此外,第二列可能是您要通过desc订购的。

CREATE VIEW vwTopCustomer
AS 
   SELECT TOP 10 
       CustomerID , 
       SUM(Quantity*Price) AS TotalMoneySpent
   FROM 
       tblCUSTOMER c
   JOIN 
       tblORDER o ON c.CustomerID = o.CustomerID
   JOIN 
       tblORDER_PRODUCT op ON o.OrderID = op.OrderID
   JOIN 
       tblPRODUCT p ON op.ProductID = p.ProductID
   GROUP BY  
       CustomerID
   ORDER BY 
       TotalMoneySpent DESC
   GO

答案 2 :(得分:1)

请注意,SQL Server将获得TOP 10行,但可能会或可能不会按照您希望显示的顺序显示。

这是sql server的限制。返回的行将是"更正" TOP 10但不按预期的ORDER BY子句的顺序排列。

从视图中进行选择时,您需要使用ORDER BY子句。

CREATE VIEW vwTopCustomer
AS 
   SELECT TOP 10  CustomerID 
             ,SUM(Quantity*Price) AS TotalMoneySpent
   FROM  tblCUSTOMER c
   JOIN  tblORDER o          ON c.CustomerID = o.CustomerID
   JOIN  tblORDER_PRODUCT op ON o.OrderID = op.OrderID
   JOIN  tblPRODUCT p        ON op.ProductID = p.ProductID
   GROUP BY   CustomerID
   ORDER BY  TotalMoneySpent DESC
GO

从视图中选择

SELECT * FROM vwTopCustomer
ORDER BY TotalMoneySpent DESC

视图中的ORDER BY

  

按指定的列列表排序查询的结果集,并且   (可选)将返回的行限制为指定范围。订单中   除非是,否则不保证在结果集中返回哪些行   指定了ORDER BY子句。

BOL Referrence