Link to home
Start Free TrialLog in
Avatar of josephdaviskcrm
josephdaviskcrmFlag for United States of America

asked on

SQL - Help building a complex query.

SELECT StoreID, Date, Score, Visit, AreaDisplay
FROM Structure
WHERE AreaID IN ('3266103') AND Visit IN ('Unannounced')
ORDER BY StoreID, Date ASC

The above SQL produces data output similar to the following

StoreID    Date                    Score    Visit                      AreaDisplay
000171   2005-06-09       37          Unannounced      3266103 BKM-JV CBM - 103
000171   2006-02-11       90          Unannounced      3266103 BKM-JV CBM - 103
...               ...                       ...             ...                            ...

Another query I'm trying to build uses aggregate functions, but it throws an error because AreaDisplay is not an aggregate function. I need the text in AreaDisplay to be returned along with the dataset.

SELECT TOP (6) AVG(Score) AS Score, AreaDisplay
FROM (
        SELECT ranking = dense_rank() over (PARTITION BY StoreID ORDER BY OERDate ASC), *
        FROM dbo.BK_OER_Structure
        WHERE AreaID IN ('3266103') AND (Visit IN ('Unannounced'))
        ) average
GROUP BY ranking

Without the AreaDisplay, the query works fine and displays:

Score
46.85
79.83
74.66
68.33
80.20
76.45

How can I get AreaDisplay to appear on every record in the return dataset as it is found in the query at the top?
ASKER CERTIFIED SOLUTION
Avatar of chapmandew
chapmandew
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of josephdaviskcrm

ASKER

Thank you sir.  You've helped me yet again.
My pleasure.