将 SQL Table 列转换为具有每个类别计数的行

Transposing SQL Table Columns to Rows with Count on Each Category

我有一个包含 12,000 行数据的 table。 table 由 7 列数据(PIDA、NIDA、SIDA、IIPA、RPRP、IORS、DDSN)组成,每列有 4 种条目类型(“支持”、“不支持”、“未编目”或“空”条目)

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

我想生成一个输出,其中每个条目都针对每一列进行计数。喜欢列到行的转置。

+---------------+------+------+------+------+
|  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 |
+---------------+------+------+------+------+

内联 select 或 case 语句没有任何运气。我有一种感觉,首先需要计算两者,然后将每个列为输出中的行

谢谢大家,

一个选择是 UNPIVOT 您的数据,然后 PIVOT 结果

例子

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

结果(小样本量)

Categories      PIDA    NIDA    SIDA    IIPA
NULL            1       1       2       3
Supported       2       3       NULL    1
Uncatalogued    1       NULL    2       NULL