如何在 SQLite 的单个 table 上从多个 countof 中获取数据?

How to do get data out of multiple `countof`s on single table in SQLite?

我有一个包含数据的 table 和一个包含日期值的列和一个关联列,它可以有 5 个不同的值(即 abc,d,e).

Table A
table_id     date    affinity

我需要计算每个 month of the year 每个 affinity 有多少条目。我最初为每个亲和力每个月创建了一个 sql 查询,因此数据库打开了大约 60 次,这对于大多数 android 手机来说太多了,无法处理,而且速度非常慢。

如何在单个查询中压缩它,然后如何获取值?理想情况下,我会创建一个临时的 table,看起来像这样,带有样本值。

    Jan    Feb    Mar    Apr    May ...
a   2      4      6      4      1
b   4      1      3      4      0
c   2      2      4      2      0
d   7      3      6      0      5
e   9      5      1      9      8

我不太精通高级 sql 查询,但我知道 JOINS 和嵌套 SELECTS。所以我只需要朝正确的方向稍微推动一下。我怎样才能做到这一点?

研究 'GROUP BY' 及其聚合函数。类似于:

SELECT COUNT() AS C, affinity, date 
FROM ...
GROUP BY affinity, date

为您提供记录列表。如有必要,重新排序为矩阵。

您可以通过结合使用 case 表达式和 count 函数来使用条件聚合来执行此操作:

select 
    affinity
    , count(case when month(`date`) = 1 then affinity end) as "Jan"
    , count(case when month(`date`) = 2 then affinity end) as "Feb"
    , count(case when month(`date`) = 3 then affinity end) as "Mar"
    , count(case when month(`date`) = 4 then affinity end) as "Apr"
    , count(case when month(`date`) = 5 then affinity end) as "May"
    -- ... etc.
from a -- this is your table, which I assumed is called 'a'
group by affinity;

Sample SQL Fiddle

由于 SQLite 没有任何 month 函数,您必须使用 strftime 函数来代替:strftime('%m', date)

对于 SQLite,查询应该看起来像这样:

select 
    affinity
    , count(case when strftime('%m', date) = '01' then affinity end) as "Jan"
    , count(case when strftime('%m', date) = '02' then affinity end) as "Feb"
    , count(case when strftime('%m', date) = '03' then affinity end) as "Mar"
    , count(case when strftime('%m', date) = '04' then affinity end) as "Apr"
    , count(case when strftime('%m', date) = '05' then affinity end) as "May"
from a -- this is your table, which I assumed is called 'a'
group by affinity;