0

In this query I am trying to get a list of distinct part numbers and the last date their status was updated. This is a working query in Access using the last() function. Since last() is only available in SQL Sever, I figured max() would do the dame thing. I have the following query in SSMS:

SELECT 
    max(DishSql2.dbo.tblMInvDetail.InvDate) AS LastOfInvDate, 
    DishSql2.dbo.tblMInvDetail.PartNo`
FROM DishSql2.dbo.tblMInvDetail
GROUP BY DishSql2.dbo.tblMInvDetail.PartNo
ORDER BY DishSql2.dbo.tblMInvDetail.InvDate DESC , DishSql2.dbo.tblMInvDetail.PartNo;

Results in :

Msg 8127, Level 16, State 1, Line 5

Column "DishSql2.dbo.tblMInvDetail.InvDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

There are only two columns, one is in the group by and and other is in the max() function. Can anyone what I'm doing wrong? Is there a better way to do this?

1 Answer 1

2

Msg 8127, Level 16, State 1, Line 5

Column "DishSql2.dbo.tblMInvDetail.InvDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

You're trying to order on the un-aggregated DishSql2.dbo.tblMInvDetail.InvDate column. What you probably want is:

SELECT 
    max(DishSql2.dbo.tblMInvDetail.InvDate) AS LastOfInvDate, 
    DishSql2.dbo.tblMInvDetail.PartNo`
FROM DishSql2.dbo.tblMInvDetail
GROUP BY DishSql2.dbo.tblMInvDetail.PartNo
ORDER BY max(DishSql2.dbo.tblMInvDetail.InvDate) DESC , DishSql2.dbo.tblMInvDetail.PartNo;
3
  • Using the alias also worked. ORDER BY must be post select, I'm used to fighting with WHERE and GROUP BY which are process before the select and so don't recognize the aliases
    – Jimbus
    Feb 1 at 17:02
  • @Jimbus Yup the alias is allowed to be referenced in the ORDER BY clause. To really blow your mind, even column ordinal is allowed too. E.g. ORDER BY 1, 2 would produce the same outcome. But it's not clean code / readable, in my opinion.
    – J.D.
    Feb 1 at 17:31
  • see this for processing order learn.microsoft.com/en-us/sql/t-sql/queries/…
    – Bob Klimes
    Feb 1 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.