sqlite db的二维选择查询

时间:2018-03-02 06:11:37

标签: sql sqlite

我想生成汇总表以显示每个模型的计数(不同的pid) 我有数据库:

model corner pid
aa  c1  1
aa  c1  1
aa  c1  2
aa  c2  3
aa  c3  4
bb  c1  1
bb  c1  1
bb  c2  2
bb  c2  3
bb  c2  3
bb  c3  4

结果如下:

corner  aa bb
c1      2   1
c2      1   2
c3      1   1

我可以知道应该使用哪种查询命令吗?

1 个答案:

答案 0 :(得分:1)

您可以先获得所需的计数:

select corner, model, count(distinct pid) as n from t group by corner, model

给你这个:

corner|model|n
c1    |aa   |2
c1    |bb   |1
c2    |aa   |1
c2    |bb   |2
c3    |aa   |1
c3    |bb   |1

然后按corner对派生的表进行分组,并根据n值对model求和:

select
    corner,
    sum(case when model = 'aa' then n else 0 end) as aa,
    sum(case when model = 'bb' then n else 0 end) as bb
from (
    select corner, model, count(distinct pid) as n
    from t
    group by corner, model
) dt
group by corner

SQLite将布尔值表示为1和0(分别为true和false),因此您可以将其写为:

select
    corner,
    sum(n * (model = 'aa')) as aa,
    sum(n * (model = 'bb')) as bb
from (
    select corner, model, count(distinct pid) as n
    from t
    group by corner, model
) dt
group by corner

但我发现便携式case版本一目了然。

任一版本都会产生如下结果:

corner|aa|bb
c1    |2 |1
c2    |1 |2
c3    |1 |1

如果您希望结果按corner排序,那么您应该在查询中包含明确的order by corner

select
    corner,
    sum(case when model = 'aa' then n else 0 end) as aa,
    sum(case when model = 'bb' then n else 0 end) as bb
from (
    select corner, model, count(distinct pid) as n
    from t
    group by corner, model
) dt
group by corner
order by corner