1

I have a table with 12,000 rows of data. The table is comprised of 7 columns of data (PIDA, NIDA, SIDA, IIPA, RPRP, IORS, DDSN) each column with 4 entry types ("Supported", "Not Supported", "Uncatalogued", or "NULL" entries)

+--------------+-----------+--------------+-----------+
|     PIDA     |   NIDA    |     SIDA     |   IIPA    |
+--------------+-----------+--------------+-----------+
| Null         | Supported | Null         | Null      |
| Uncatalogued | Supported | Null         | Null      |
| Supported    | Supported | Uncatalogued | Supported |
| Supported    | Null      | Uncatalogued | Null      |
+--------------+-----------+--------------+-----------+

I would like to generate an output where each entry is counted for each column. Like column to row transpose.

+---------------+------+------+------+------+
|  Categories   | PIDA | NIDA | SIDA | IIPA |
+---------------+------+------+------+------+
| Supported     |   10 |   20 |   50 |    1 |
| Non Supported |   30 |   50 |   22 |    5 |
| Uncatalogued  |    5 |   10 |   22 |   22 |
| NULL          |   10 |   11 |   22 |   22 |
+---------------+------+------+------+------+

Not having any luck with inline select or case statements. I have a feeling a little bit of both would be needed to first count and then list each as row in the output

Thanks all,

NanoNet
  • 218
  • 3
  • 11
  • Sounds like you need a `PIVOT`. Does [THIS](https://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns-in-sql-server) give you a starting place? – WAMLeslie Apr 30 '21 at 17:07

1 Answers1

1

One option is to UNPIVOT your data and then PIVOT the results

Example

Select *
 From  (
        Select B.* 
         From  YourTable A
         Cross Apply ( values (PIDA,'PIDA',1)
                             ,(NIDA,'NIDA',1)
                             ,(SIDA,'SIDA',1)
                             ,(IIPA,'IIPA',1)
                     ) B(Categories,Item,Value)
       ) src
 Pivot ( sum(Value) for Item in ([PIDA],[NIDA],[SIDA],[IIPA] ) ) pvt

Results (with small sample size)

Categories      PIDA    NIDA    SIDA    IIPA
NULL            1       1       2       3
Supported       2       3       NULL    1
Uncatalogued    1       NULL    2       NULL
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66