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

时间:2015-10-04 13:58:31

标签: sqlite android-sqlite

我有一个包含数据的表,并且有一个包含日期值和关联列的列,它可以有5个不同的值(即abc,{{ 1}},d)。

e

我需要计算每Table A table_id date affinity month of the year个条目的数量。我最初为每个月的亲和力创建一个sql查询,因此数据库被打开了大约60次,这对于大多数Android手机来说太多了,并且速度非常慢。

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

affinity

我不熟悉高级sql查询,但我知道JOINS和嵌套SELECTS。所以我只需要朝着正确的方向努力。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

调查'GROUP BY'及其聚合函数。类似的东西:

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

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

答案 1 :(得分:1)

您可以使用条件聚合将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;