如何对产品进行分组,然后按SQL中的日期desc对它们进行排序?

时间:2013-08-11 03:29:07

标签: sql qtsql

这是SQL,但它给了我一个错误:

select u.productId, count(ProductID) as total, p.Name 
from dbo.UserXProduct AS u 
INNER JOIN dbo.product AS p ON u.ProductID = p.ID   
group by productid, p.name 
having count(ProductID) > 5 
order by u.dateEntered desc, total desc

编辑:这是我得到的错误:

  

“dbo.UserXProduct.DateEntered”列在ORDER BY中无效   子句,因为它不包含在聚合函数或   GROUP BY子句

2 个答案:

答案 0 :(得分:1)

您无法直接通过u.dateEntered订购。但是,您可以按max(u.dateEntered)订购。这可能是你想要的最新产品:

select u.productId, count(ProductID) as total, p.Name 
from dbo.UserXProduct AS u 
INNER JOIN dbo.product AS p ON u.ProductID = p.ID   
group by productid, p.name 
having count(ProductID) > 5 
order by max(u.dateEntered) desc, total desc

答案 1 :(得分:0)

您无法在group by中引用列别名。试试这个:

select u.productId, count(ProductID) as total, p.Name 
from dbo.UserXProduct AS u 
INNER JOIN dbo.product AS p ON u.ProductID = p.ID   
group by productid, p.name 
having count(ProductID) > 5 
order by count(ProductID) desc

您不能ORDER BY u.dateEntered列,除非它出现在group by中。