Hello, thanks in advance for any help.
I have a query like this:
select distinct StudentID, Description ,sifn.AccomodationFlag, sifn.Name, sifn.labelorder
from StudentInfoFields sif
inner join StudentInfoFieldNames sifn
ON sifn.RecordID = InfoID and sif.Description <> ''
WHERE name='EquipmentCode_1' OR name= 'temp OrcaCardFlag' OR name= 'temp OrcaCardFlag'
OR name='Monitor: (MONIT)' OR name='MustBeReceived (YES/NO)'
I got result like below
I would like to roll up some rows to columns, and one record for one student,
for example the first student 21012,
I would it become something like below: How can I achieve below? also if I want to add accomadationflag in below, which could be yes or no, is there a way to do that, the latter question is not important as the first one, if cannot do, it is ok.
August 13, 2022 at 4:39 pm
With > 50,000 points, I should not need to tell you this, but please provide your test data in consumable format, not as an image.
Note also the correct spelling of 'accommodation'
The absence of evidence is not evidence of absence.
Martin Rees
You can lead a horse to water, but a pencil must be lead.
Stan Laurel
Generally speaking the easiest way to achieve your "roll up" is to use a GROUP BY on StudentID and then for each of your names do a MAX or MIN, i.e. as an example:
SELECT StudentID, MIN(CASE WHEN name = 'EquipmentCode_1' THEN Description END) AS EquipmentCode_1, ... etc.
FROM ...
GROUP BY StudentID
Try it.
August 15, 2022 at 4:57 pm
Thank you Kaj, that was a great and easy trick.
Thank you so much!
August 15, 2022 at 6:22 pm
Thank you Kaj, that was a great and easy trick.
Thank you so much!
The method Kaj wrote about is call a "CROSS TAB". You can read more about how it works here because Microsoft Removed it from their documentation when PIVOT came out. The article also explains why you may want to avoid PIVOT. The 2nd article is based on the first but tells you how you can create the Dynamic SQL to handle an unknown number of columns. Both articles are quite old but just as relevant today.
https://www.sqlservercentral.com/articles/cross-tabs-and-pivots-part-1-converting-rows-to-columns-1
https://www.sqlservercentral.com/articles/cross-tabs-and-pivots-part-2-dynamic-cross-tabs
--Jeff Moden
Change is inevitable... Change for the better is not.
August 16, 2022 at 10:03 pm
Thank you so much Jeff, that is good information, I will read and look into it. Thank you for providing the links !
August 17, 2022 at 1:48 am
You're welcome and thank you for the feedback.
The articles are based on "pivoting" numeric values but you can do like Kaj suggested and use Min or Max to pivot text. I normally recommend using MAX just to set a standard.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply