0
SELECT DISTINCT AppID,
                CASE
                  WHEN Category = '< 18 years old' THEN 'yes'
                  ELSE ''
                END AS '<18years old',
                CASE
                  WHEN Category = 'SSN Exists' THEN 'yes'
                  ELSE ''
                END AS 'Applicant has SSN',
                CASE
                  WHEN Category = 'Self Employed' THEN 'yes'
                  ELSE ''
                END AS 'Self employed'
FROM   Table1
WHERE  AppID = 123 

OUTPUT Desired I am trying to produce the results below where each AppID has only 1 line with all the information pertinent to it. The code above produces multiple lines for each application. I tried to put the case statements all together with 1 END, but I get an error when I use Aliases before the END keyword. Thanks

AppID         <18 Year old           Applicant has SSN           Self employed  

123     yes         yes
124                 yes         yes
125                 yes         yes
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
user1860212
  • 555
  • 3
  • 7
  • 8

4 Answers4

1

You need a group by rather than a distinct:

SELECT AppID,
       max(CASE WHEN Category = '< 18 years old' THEN 'yes'
                ELSE ''
           END) AS '<18years old',
       max(CASE WHEN Category) = 'SSN Exists' THEN 'yes'
                ELSE ''
           END) AS 'Applicant has SSN',
       max(CASE WHEN Category = 'Self Employed' THEN 'yes'
                ELSE ''
           END) AS 'Self employed'
FROM   Table1
WHERE  AppID = 123
group by AppId
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks for your reply. Why would I use a MAX function if I do not look for a maximum value ? Is the MAX function - will help all values appear on the same line ? – user1860212 Nov 29 '12 at 19:37
0

You can nest the Case statements as follows and just alias at the end:

CASE WHEN 
    Category = '< 18 years old' 
THEN 'yes'
ELSE
    CASE WHEN
        Category = 'SSN Exists'
    THEN 'yes'
    ELSE
        ...
        ...
    END
END AS Alias

Is that what you're after?

beyond-code
  • 1,423
  • 1
  • 12
  • 20
0

Your aliases should not be enclosed in ''.

Check on your DB Engine which type of character you must use to enclose aliases.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
0

If I understand your problem correctly, you need to do a GROUP BY:

SELECT  AppID,
        MAX(CASE
          WHEN Category = '< 18 years old' THEN 'yes'
          ELSE ''
        END) AS '<18years old',
        MAX(CASE
          WHEN Category = 'SSN Exists' THEN 'yes'
          ELSE ''
        END) AS 'Applicant has SSN',
        MAX(CASE
          WHEN Category = 'Self Employed' THEN 'yes'
          ELSE ''
        END) AS 'Self employed'
FROM   Table1
WHERE  AppID = 123 
GROUP BY AppID
Lamak
  • 69,480
  • 12
  • 108
  • 116