0

I was wondering how I can take a data set that looks like this:

Table 1:

RecordID    Code
A   351
A   352
A   353
A   354

to look like this:

Table 2:

you can already assume I created a second table with the column headers I created below

RecordID    351 352 353 354 355 356
   A         Y   Y   Y   Y   N   N

Thank you in advance for your help.

2
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Dec 30, 2015 at 21:59
  • I am using SQLServer 2012 Commented Dec 30, 2015 at 22:01

2 Answers 2

1
SELECT RecordID,
    CASE WHEN SUM(CASE WHEN Code = 351 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [351],
    CASE WHEN SUM(CASE WHEN Code = 352 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [352],
    CASE WHEN SUM(CASE WHEN Code = 353 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [353],
    CASE WHEN SUM(CASE WHEN Code = 354 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [354],
    CASE WHEN SUM(CASE WHEN Code = 355 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [355],
    CASE WHEN SUM(CASE WHEN Code = 356 THEN 1 ELSE 0 END) = 1 THEN 'Y' ELSE 'N' AS [356]
FROM yourTable
GROUP BY RecordID
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks guys! this makes sense and should work, ill give it a shot.
0

you can try something like this:

select
    RecordID,
    iif(sum(iif([Code]=351,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=352,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=353,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=354,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=355,1,0))>0,'Y','N'),
    iif(sum(iif([Code]=356,1,0))>0,'Y','N')
from table
group by RecordID

5 Comments

That's an interesting way of doing it. Why not just use max(case when code = 351 then 'Y' else 'N' end)
@Lock in this case we will depend on the order of ascii codes, what if we need to localize or use other symbols?
@Lashlane. Not sure I see what localization has to do with this? Don't get me wrong.. I'm not saying yours is in anway wrong.. just never seen it done like that and to me the intent isn't as clear. Can you explain how this affects the order of ascii codes?
@Lock your approach works only because ascii code of Y > N, for example in russian it will be vice versa (Д (yes) < Н (no)), so for russian letters you need to use min
@Lashlane Ah I see what you mean now. I didn't full understand the question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.