Friday, August 17, 2012

get above aggregate average values in MSSQL

Share photos on twitter with Twitpic

The values of above average length may be queried out of the table above like so:

SELECT myValue FROM myTable
WHERE LEN(myValue) > (
   SELECT AVG(LEN(myValue)) FROM myTable
)

 
 

If we wanted to filter out the duplicates first, be would still get the same average length (4), but the end result set would be truncated of the dupes. A query for as much is:

CREATE TABLE #myTempTable
(
   myTempValue nvarchar(50)
)
DECLARE @myWord nvarchar(50)
 
DECLARE curs CURSOR FOR
SELECT DISTINCT myValue FROM myTable
OPEN curs
FETCH NEXT FROM curs into @myWord
WHILE @@FETCH_STATUS = 0
   BEGIN
      INSERT INTO #myTempTable (myTempValue)
      VALUES (@myWord)
      FETCH NEXT FROM curs into @myWord
   END
CLOSE curs
DEALLOCATE curs
 
SELECT myTempValue FROM #myTempTable
WHERE LEN(myTempValue) > (
   SELECT AVG(LEN(myTempValue)) FROM #myTempTable
)
 
DROP TABLE #myTempTable

No comments:

Post a Comment