If Having More Than x Then Where Statement

  • Is there anyway to have HAVING and WHERE clauses work in conjecture with each other?

    ie psuedocode:

    CASE

    HAVING count(children) > 3 THEN WHERE nationality = 'Mexican'

    HAVING count(children) = 2 THEN WHERE nationality = 'American'

    HAVING count(children) = 1 THEN WHERE nationality = 'Japanese'

    END

  • Nope, look up dynamic SQL, if you provide some DDL i can help you with some dynamic SQL to complete your task

    ***The first step is always the hardest *******

  • guerillaunit (8/7/2012)


    Is there anyway to have HAVING and WHERE clauses work in conjecture with each other?

    ie psuedocode:

    CASE

    HAVING count(children) > 3 THEN WHERE nationality = 'Mexican'

    HAVING count(children) = 2 THEN WHERE nationality = 'American'

    HAVING count(children) = 1 THEN WHERE nationality = 'Japanese'

    END

    WHERE happens before the GROUP BY calculations, HAVING after. Thats really the only difference. You can only have one of each in a query. There is however no reason you can't put nationality = 'American' in your HAVING clause. Try this:

    HAVING (

    COUNT(children) > 3 AND nationality = 'Mexican'

    )

    OR (

    COUNT(children) = 2 AND nationality = 'American'

    )

    OR (

    COUNT(children) = 1 AND nationality = 'Japanese'

    )

    If I understood what you are trying to do this should cover it.

    Kenneth FisherI was once offered a wizards hat but it got in the way of my dunce cap.--------------------------------------------------------------------------------For better, quicker answers on T-SQL questions, click on the following... http://www.sqlservercentral.com/articles/Best+Practices/61537/[/url]For better answers on performance questions, click on the following... http://www.sqlservercentral.com/articles/SQLServerCentral/66909/[/url]Link to my Blog Post --> www.SQLStudies.com[/url]

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply