Android查询多列获取计数

时间:2017-03-16 02:56:38

标签: android sqlite select group-by multiple-columns

我正在尝试查询表并获得一个结果,该结果将显示包含10列的表中的所有水果条目。这是表结构。

    Table 1
    Name          Col2    Col3      ...    Col11
    Apple Pie     Apple   Cinnamon  ...    Flour
    Sugar Cookie  Flour   Sugar     ...    Vanilla

我已经尝试过这个SQL查询,结果接近我正在寻找的内容。

    SELECT
    Col2 as Flavor, COUNT(*)
    FROM
    table 1
    group by Flavor

我遇到的问题是弄清楚如何获取查询中的其他9列。预期的结果应该是。

    Flavor      Count
    Apple       1
    Cinnamon    1
    Flour       2
    Sugar       1
    Vanilla     1

感谢所有引导我朝正确方向发展的评论。任何人都可以帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您可以按如下方式获取列表中项目的出现位置:

import java.util.Collections;

// count the occurrence of item one in the list
int itemOneCount =  Collections.frequency(listitem,"item one");

答案 1 :(得分:0)

再次感谢您的帮助!评论引导我找到正确的答案。这是解决方案。

    SELECT SUM(Output.count),Output.attr 
    FROM
    (
    SELECT COUNT(flv1name) AS count,flv1name AS attr FROM recipes GROUP BY flv1name 
    UNION ALL
    SELECT COUNT(flv2name) AS count,flv2name AS attr FROM recipes GROUP BY flv2name
    UNION ALL
    SELECT COUNT(flv3name) AS count,flv3name AS attr FROM recipes GROUP BY flv3name
    UNION ALL
    SELECT COUNT(flv4name) AS count,flv4name AS attr FROM recipes GROUP BY flv4name
    UNION ALL
    SELECT COUNT(flv5name) AS count,flv5name AS attr FROM recipes GROUP BY flv5name
    UNION ALL
    SELECT COUNT(flv6name) AS count,flv6name AS attr FROM recipes GROUP BY flv6name
    UNION ALL
    SELECT COUNT(flv7name) AS count,flv7name AS attr FROM recipes GROUP BY flv7name
    UNION ALL
    SELECT COUNT(flv8name) AS count,flv8name AS attr FROM recipes GROUP BY flv8name
    UNION ALL
    SELECT COUNT(flv9name) AS count,flv9name AS attr FROM recipes GROUP BY flv9name
    UNION ALL
    SELECT COUNT(flv10name) AS count,flv10name AS attr FROM recipes GROUP BY flv10name) AS Output

    GROUP BY attr

这会将结果显示为

    SUM.Output.Count     attr
    1                    Apple
    1                    Cinnamon
    2                    Flour
    1                    Sugar
    1                    Vanilla