The following query is working fine without ‘,MAX(Row)’
WITH QResult AS
(SELECT
ROW_NUMBER() OVER (ORDER BY Ad_Date DESC) AS Row,
*
FROM [vw_ads]
)
SELECT *, MAX(Row)
FROM QResult
When MAX(Row) is added, SQL Server 2008 is throwing the following error :
Column ‘QResult.Row’ is invalid in the select list because it is not
contained in either an aggregate function or theGROUP BYclause.
When using an aggregate function like
SUM,COUNTorMAX, and you want to also select other columns from your data, then you need to group your data by the other column(s) used in your query.So you need to write something like:
This also means you need to explicitly spell out the columns you want – a good idea in any case. You cannot use
*in aGROUP BYclause.Update: based on your comment, I guess what you really want is something like this:
(see Update #2 – Martin Smith’s suggestion is even better than my original idea here)
This will give you the maximum value of
Rowfrom the CTE, the same value, for each row of your result set.Update #2: Martin Smith’s suggestion would be this:
and of course, this works, too – and even more efficient than my solution. Thanks, Martin!