sqlite计算并对一个查询中的每一列进行分组

时间:2017-03-09 11:28:39

标签: sql sqlite

我有下表:

SCORE1    SCORE2    SCORE3
P         P         F
P         P         T
D         P         F
D         D         T
P         P         F
P         D         T

我希望对每个列进行计数和分组,以便获取SCORE1SCORE2的P和D的数量,以及SCORE3的T和F的数量。

我虽然可能像这样做了

select SCORE1, count(SCORE1) as SCORE1_counts,
       SCORE2, count(SCORE2) as SCORE2_counts,
       SCORE3, count(SCORE3) as SCORE3_counts,
from mytable
group by SCORE1,SCORE2,SCORE3.

但是,对于组中列的每个唯一组合,这将会返回一行,其中我想要的是:

SCORE1    SCORE1_counts    SCORE2    SCORE2_counts    SCORE3    SCORE3_counts
P         4                P         4                T         3
D         2                D         2                F         3

只需一个sqlite查询,我想要的是什么?

1 个答案:

答案 0 :(得分:2)

我认为您最好在中获取值,而不是列。这样做是否符合你的要求:

select 'SCORE1' as which, count(*) as counts,
from mytable
group by Score1
union all
select 'SCORE2' as which, count(*) as counts,
from mytable
group by Score2
union all
select 'SCORE3' as which, count(*) as counts,
from mytable
group by Score3;