Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use pivot to find the records with the most columns populated?

I have a problem where I have 5 columns.

enter image description here

What I want to do is add a count on the end with the number of columns where there is no null value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am trying to use pivot as this seems to be the most logical SQL clause. Any ideas on this? I haven’t used Pivot in many instances so this is new for me.

>Solution :

An inline pivot/conditional aggregate and a COUNT seems to be what you want here. As all your columns have different data types, you need to also use some CASE expressions. Something like this:

SELECT ID,
       a,
       ...
       (SELECT COUNT(V.C)
        FROM (VALUES(CASE WHEN a IS NOT NULL THEN 1 END),
                    (CASE WHEN b IS NOT NULL THEN 1 END),
                    (CASE WHEN c IS NOT NULL THEN 1 END),
                    (CASE WHEN d IS NOT NULL THEN 1 END),
                    (CASE WHEN e IS NOT NULL THEN 1 END),
                    (CASE WHEN f IS NOT NULL THEN 1 END))V(C)) AS NonNullColumns
FROM dbo.YourTable;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading