Question

I have a dynamic stored procedure that start as follows with the declaration of a temp table and then an insert statement.

Can someone here tell me how I need to adapt the following line so that it creates a rank based on the groupCount (desc) instead of by Count?

When I just say groupCount instead of Count then it returns:

Invalid column name 'groupCount'

The line in question:

RANK() OVER(ORDER BY COUNT(*) desc, <sel>) [Rank],

My procedure (first part):

   SET @sql = N' DECLARE @temp AS TABLE
    (
                ranking int,
                item nvarchar(100),
                totalCount int,
                matchCount int,
                groupCount int,
                groupName nvarchar(100)
    )

    INSERT INTO @temp
    (
                ranking,
                item,
                totalCount,
                matchCount,
                groupCount,
                groupName
    )
    SELECT      RANK() OVER(ORDER BY COUNT(*) desc, <sel>) [Rank],
                <sel>,
                COUNT(*) AS totalCount,
                SUM(CASE WHEN suggestedAction = recommendation THEN 1 ELSE 0 END) AS matchCount,
                ROUND(100 * AVG(CASE WHEN suggestedAction = recommendation THEN 1.0 ELSE 0.0 END), 0) AS groupCount,
                ''currentMonth'' AS groupName
    FROM        LogEsc
    WHERE       dateEsc LIKE ''' + @date0 + '%''
    AND         EID LIKE ''PE%''
    GROUP BY    <sel>
    ORDER BY    groupCount desc, <sel>
        -- ...

Many thanks in advance for any help with this, Tim.

Was it helpful?

Solution

You can't use the alias.

use

ORDER BY ROUND(100 * AVG(CASE WHEN suggestedAction = recommendation THEN 1.0 ELSE 0.0 END), 0) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top