如何计算特定值列?

时间:2014-04-03 12:44:56

标签: mysql sql

我使用mysql制作了包含4列的表。

每列的数据类型为BIT

我有这样的数据:

ColA  ColB ColC Cold
1     1    1     1
1     0    0     1
0     0    1     0

我希望查询能够返回列名和nos of 1s,如下所示:

ColA ColB ColC Cold
2    1    2    2

我已经考虑过group by,aggregate function,但是无法设计查询。

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

从你的评论到AK47的答案,你可能更喜欢

select 
sum(colA) as colA, 
sum(colB) as colB, 
sum(colC) as colC, 
sum(colD) as cold -- I'm frozen
from Table1

查看sqlFiddle

中的差异

答案 1 :(得分:1)

试试这个,

Select 'ColA',Sum(ColA) from myTable
Union All
Select 'ColB',Sum(ColB) from myTable
Union All
Select 'ColC',Sum(ColC) from myTable
Union All
Select 'ColD',Sum(ColD) from myTable

答案 2 :(得分:1)

阿什法克,   我想你想做的是:

SELECT 'ColA' AS COL, (SELECT COUNT(1) FROM tab WHERE ColA=1) UNION ALL
SELECT 'ColB' AS COL, (SELECT COUNT(1) FROM tab WHERE ColB=1) UNION ALL
SELECT 'ColC' AS COL, (SELECT COUNT(1) FROM tab WHERE ColC=1) UNION ALL
SELECT 'ColD' AS COL, (SELECT COUNT(1) FROM tab WHERE ColD=1)

我希望它会帮助你