有什么方法可以在tSQL的不同列中汇总分组?

时间:2018-08-22 11:42:04

标签: sql sql-server tsql pivot

我有几列具有不同数量的相同值:

+---+---+---+
| A | B | C |
+---+---+---+
| 1 | 4 | 4 |
| 2 | 4 | 3 |
| 2 | 4 | 3 |
| 4 | 4 | 3 |
| 3 | 2 | 3 |
| 3 | 1 | 2 |
| 3 | 3 | 2 |
| 1 | 1 | 1 |
+---+---+---+

我想要计算每个值的总数并返回如下输出:

+---+---+---+---+
|   | A | B | C |
+---+---+---+---+
| 1 | 2 | 2 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 3 | 1 | 4 |
| 4 | 1 | 4 | 1 |
+---+---+---+---+

据我所知,透视操作将仅允许您计算单个列中的响应数。

任何帮助表示感谢!

欢呼

3 个答案:

答案 0 :(得分:1)

您可以使用apply

select colv, 
       sum(case when colname = 'A' then 1 else 0 end) as [A],
       sum(case when colname = 'B' then 1 else 0 end) as [B],
       sum(case when colname = 'C' then 1 else 0 end) as [C]
from table t cross apply
    ( values ('A', A), ('B', B), ('C', C) 
    ) tt (colname, colv)
group by colv;

答案 1 :(得分:0)

您可以执行UNPIVOTCOUNTPIVOT

DECLARE @DataSource TABLE
(
    [A] INT
   ,[B] INT
   ,[C] INT
);

INSERT INTO @DataSource ([A], [B], [C])
VALUES (1, 4, 4)
      ,(2, 4, 3)
      ,(2, 4, 3)
      ,(4, 4, 3)
      ,(3, 2, 3)
      ,(3, 1, 2)
      ,(3, 3, 2)
      ,(1, 1, 1);

SELECT *
FROM
(
    SELECT [column]
          ,[value]
          ,COUNT(*) AS [count]
    FROM @DataSource
    UNPIVOT
    (
        [value] FOR [column] IN ([A], [B], [C])
    ) UNPVT
    GROUP BY [column]
            ,[value]
) DS
PIVOT
(
  MAX([count]) FOR [column] IN ([A], [B], [C])
) PVT;

enter image description here

答案 2 :(得分:0)

如果列数有限并且可能的值也为limitid,则可以使用多个CTE和UNION(ALL)结果:

WITH CTE_1 AS 
(
    SELECT 1 AS Col, COUNT(*) AS A,
         ( SELECT COUNT(*) AS B FROM T AS T2 WHERE B = 1 ) AS B,
         ( SELECT COUNT(*) AS C FROM T AS T3 WHERE C = 1 ) AS C
    FROM T
    WHERE A = 1
)
, CTE_2 AS 

(
    SELECT 2 AS Col, COUNT(*) AS A,
         ( SELECT COUNT(*) AS B FROM T AS T2 WHERE B = 2 ) AS B,
         ( SELECT COUNT(*) AS C FROM T AS T3 WHERE C = 2 ) AS C
    FROM T
    WHERE A = 2
)
, CTE_3 AS 

(
    SELECT 3 AS Col, COUNT(*) AS A,
         ( SELECT COUNT(*) AS B FROM T AS T2 WHERE B = 3 ) AS B,
         ( SELECT COUNT(*) AS C FROM T AS T3 WHERE C = 3 ) AS C
    FROM T
    WHERE A = 3
)
 , CTE_4 AS 

(
    SELECT 4 AS Col, COUNT(*) AS A,
         ( SELECT COUNT(*) AS B FROM T AS T2 WHERE B = 4 ) AS B,
         ( SELECT COUNT(*) AS C FROM T AS T3 WHERE C = 4 ) AS C
    FROM T
    WHERE A = 4
)

SELECT * FROM CTE_1 UNION ALL SELECT * FROM CTE_2 UNION ALL SELECT * FROM CTE_3 UNION ALL SELECT * FROM CTE_4