Home Forums SQL Server 2008 T-SQL (SS2K8) Urgent Query help needed- calculate one field based on other field in SELECT statment RE: Urgent Query help needed- calculate one field based on other field in SELECT statment

  • erikd (4/15/2013)


    dhananjay.nagarkar (4/14/2013)


    Sure I would love to share-

    Here's what I did-

    created 3 temp tables with the filelds I need for each with same order, data type.

    then UNION the 3 selects.

    then in the UNION i calculated the field as below-

    SELECT A.*,

    CASE

    WHEN [Age (Working Days)] IS NULL

    THEN NULL -- DO NOT DISLAY THIS FIELD IF AGE WORKING DAYS IS NULL

    ELSE -- DISPLAY AGE GROUP WHEN AGE IS PRESENT

    CASE

    WHEN CAST([Age (Working Days)] AS INT) < 30

    THEN '1 - 29'

    WHEN CAST([Age (Working Days)] AS INT) < 60

    THEN '30 - 59'

    WHEN CAST([Age (Working Days)] AS INT) < 90

    THEN '60 - 89'

    WHEN CAST([Age (Working Days)] AS INT) < 120

    THEN '90 - 119'

    ELSE'120 +'

    END

    END AS [Age Group (Working Days)]

    FROM (

    SELECT * FROM #tmp_JP

    UNION

    SELECT * FROM #tmp_WO

    UNION

    SELECT * FROM #tmp_WOR

    )A

    Thanks

    Dhananjay

    Doesn't everything get cast as either <120 or Over 120, or NULL? You didn't set any lower limits on your higher numbers?

    WHEN CAST([Age (Working Days)] AS INT) < 30

    THEN '1 - 29'

    WHEN CAST([Age (Working Days)] AS INT) between 30 and 59

    THEN '30 - 59'

    WHEN CAST([Age (Working Days)] AS INT) between 60 and 89

    THEN '60 - 89'

    WHEN CAST([Age (Working Days)] AS INT) between 90 and 119

    THEN '90 - 119'

    ELSE '120 +'

    Actually, no. If working days is less than 30 then the first WHEN is satisfied. If working days is less than 60, then the second WHEN is satisfied. If you flipped the CASE and started with the largest value first, then yes you would need the lower bounds defined as well. The CASE stops evaluating when it hits the first successful condition.