如何按SQL中的最大行数排序

时间:2018-01-05 15:50:10

标签: sql stored-procedures

我有这个存储过程,我想按总结果返回次数排序。意味着拥有最大订单的客户必须先来,等等 以下是我的存储过程。

BEGIN
  SELECT    Customer.Customer_Name, Item.Item_Name, 
       Count(Item.Item_Name)  , Customer_Sale.Quantity_Customer,
       Customer_Sale.Sale_Price ,Customer_Sale.Total_Price,  
       Customer_Sale.Date ,Total_Remaining_Previous, Today_Credit, 
       Total_Remaining_Now  , Today_Receiving , Total_Xhot
FROM         Customer  JOIN
                         Customer_Sale ON Customer.Customer_Id = Customer_Sale.Customer_Id INNER JOIN
                         Customer_Account on Customer.Customer_Id=Customer_Account.Customer_Id inner join 
                         Unit ON Customer_Sale.Unit_Id = Unit.Unit_Id INNER JOIN
                         Item ON Customer_Sale.Item_Id = Item.Item_Id 

                         WHERE  Customer_Sale.Date = @date and Customer_Account.Customer_Date=@date 
                          group by Item.Item_Name

END

3 个答案:

答案 0 :(得分:0)

您可以将查询包装在括号中并执行SELECT * FROM () ORDER BY ORDER_COLUMN_NAME吗?

答案 1 :(得分:0)

我假设“Count(Item.Item_Name)”是你的尝试。 你必须像这样使用Over子句:

SELECT
Customer.Customer_Name
,Item.Item_Name
,Count(Item.ID) OVER (PARTITION BY Customer.Customer_Name) AS ItemCount
,Customer_Sale.Quantity_Customer
,Customer_Sale.Sale_Price
,Customer_Sale.Total_Price
,Customer_Sale.Date
,Total_Remaining_Previous
,Today_Credit
,Total_Remaining_Now
,Today_Receiving
,Total_Xhot

这     顾客 内部联接     Customer_Sale     上         Customer.Customer_Id = Customer_Sale.Customer_Id 内部联接     客户账户     上         Customer.Customer_Id = Customer_Account.Customer_Id 内部联接     单元     上         Customer_Sale.Unit_Id = Unit.Unit_Id 内部联接     项目     上         Customer_Sale.Item_Id = Item.Item_Id 哪里     Customer_Sale.Date = @date AND Customer_Account.Customer_Date = @date

答案 2 :(得分:0)

你能试试吗

BEGIN
        SELECT   Customer.Customer_Name ,
                 Item.Item_Name ,
                 COUNT(Item.Item_Name) ,
                 Customer_Sale.Quantity_Customer ,
                 Customer_Sale.Sale_Price ,
                 Customer_Sale.Total_Price ,
                 Customer_Sale.Date ,
                 Total_Remaining_Previous ,
                 Today_Credit ,
                 Total_Remaining_Now ,
                 Today_Receiving ,
                 Total_Xhot
        FROM     Customer
                 JOIN Customer_Sale ON Customer.Customer_Id = Customer_Sale.Customer_Id
                 INNER JOIN Customer_Account ON Customer.Customer_Id = Customer_Account.Customer_Id
                 INNER JOIN Unit ON Customer_Sale.Unit_Id = Unit.Unit_Id
                 INNER JOIN Item ON Customer_Sale.Item_Id = Item.Item_Id
        WHERE    Customer_Sale.Date = @date
                 AND Customer_Account.Customer_Date = @date
        GROUP BY Item.Item_Name;
        ORDER BY COUNT(1) OVER (PARTITION BY Customer.Customer_Name) DESC
    END;