Results 1 to 2 of 2
  1. #1
    Join Date
    May 2005
    Posts
    40

    Unanswered: Rewrite a query efficiently

    Is there a efficient way to write this query?

    SELECT CASE
    WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END AS Population_Range,
    COUNT(CASE WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END) AS [No. Of Countries]
    FROM Country
    GROUP BY
    CASE WHEN Population BETWEEN 0 AND 100 THEN '0-100' WHEN Population BETWEEN 101 AND 1000 THEN '101-1000' ELSE 'Greater than 1000' END

  2. #2
    Join Date
    Jun 2003
    Location
    Ohio
    Posts
    12,592
    Provided Answers: 1
    The CASE statement embedded in you COUNT function is unnecessary:
    Code:
    SELECT	CASE 
    	WHEN Population BETWEEN 0 AND 100 THEN '0-100'
    	WHEN Population BETWEEN 101 AND 1000 THEN '101-1000'
    	ELSE 'Greater than 1000' END AS Population_Range, 
    	COUNT(*) AS [No. Of Countries]
    FROM	Country
    GROUP BY CASE
    	WHEN Population BETWEEN 0 AND 100 THEN '0-100'
    	WHEN Population BETWEEN 101 AND 1000 THEN '101-1000'
    	ELSE 'Greater than 1000' END
    If it's not practically useful, then it's practically useless.

    blindman
    www.chess.com: "sqlblindman"
    www.LobsterShot.blogspot.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •