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

  • 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 +'