[英]How to sort by Maximum number of rows in SQL
I have this stored procedure and I want to sort by number of total result returns. 我有此存储过程,我想按总结果返回数进行排序。 Means customer with maximum orders must come first and so on Following is my stored procedure. 意味着拥有最大订单的客户必须排在第一位,以此类推。以下是我的存储过程。
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
您可以将查询括在括号中并执行SELECT * FROM () ORDER BY ORDER_COLUMN_NAME
吗?
I am Assuming that the “Count(Item.Item_Name)” is your attempt at this. 我假设“ Count(Item.Item_Name)”是您的尝试。 You have to use the Over clause like this: 您必须像这样使用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
FROM Customer INNER 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 来自客户内部联接客户_销售ON Customer.Customer_Id = Customer_Sale.Customer_Id内部联接客户_帐户ON客户.Customer_Id =客户_帐户.Customer_Id内部联接单位ON Customer_Sale.Unit_Id = Unit.Unit_Id内部联接项目ON Customer_Sale.Item_Id = Item.Item_Id WHERD客户= @date AND Customer_Account.Customer_Date = @date
Can you try 你能试一下吗
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.