1

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

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

结果应该是:

Category Value
Column1    2
Column2    3
Column3    0

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

谢谢

4

3 回答 3

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 文档

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

于 2013-08-01T05:50:33.113 回答
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

于 2013-08-01T05:38:27.163 回答
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
于 2013-08-01T05:52:25.480 回答