SQL Count / Sum显示列为行

时间:2013-08-01 05:34:14

标签: sql rows

我有一个包含4位列的表 我需要创建一个报告,显示每列的所有“true”值的总和,但我需要列名作为一行返回。 例如,该表将包含:

Column1 Column2 Column3
1          1      0
0          1      0
1          1      0

结果应为:

Category Value
Column1    2
Column2    3
Column3    0

该表有其他列,我只需要特定的列

由于

3 个答案:

答案 0 :(得分:1)

我不知道是否有其他方法,但以下情况应该有效:

select 'Column1' as "Category", sum(column1) as "Value" from my_table union
select 'Column2', sum(column2) from my_table union
select 'Column3', sum(column3) from my_table

这是一个SQLFiddle

答案 1 :(得分:1)

您可以在桌面上尝试UNPIVOT(这适用于SQL Server)

create table Test (Column1 bit, Column2 bit, Column3 bit)

insert into Test values (1,1,0)
insert into Test values (0,1,0)
insert into Test values (1,1,0)

SELECT Value, sum(Vals)
FROM
   (CONVERT(INT, Column1) Column1, CONVERT(INT, Column2) Column2, CONVERT(INT, Column3) Column3
   FROM Test) p
UNPIVOT
   (Vals FOR Value IN
      (Column1, Column2, Column3)
)AS unpvt
GROUP BY Value

PIVOT/UNPIVOT documentation

http://sqlfiddle.com/#!6/957c6/1/0

答案 2 :(得分:0)

试试这个:

select 
category = "column1", value = sum (convert(int,col1)) from MyTable1
union
select 
category = "column2", value = sum (convert(int,col2)) from MyTable1
union
select 
category = "column3", value = sum (convert(int,col3)) from MyTable1