使用每组所需的多个记录值进行分组?

时间:2014-02-17 22:08:08

标签: sqlite group-by having

数据库的简化版本:

fkey|count1|count2|count3|feature
100|0|1|0|feature1
100|0|1|0|feature1
100|0|1|0|feature2

101|0|1|0|feature3
101|0|1|0|feature4

102|1|0|0|feature3
102|1|0|0|feature4

103|0|0|1|feature1
103|0|0|1|feature2

104|0|0|1|feature1
104|0|0|1|feature1
104|0|0|1|feature2
104|0|0|1|feature3

我想知道哪些fkeys与feature1和feature2相关联(在现实生活中,功能列表可以达到10或20)。我还想要feature1和feature2的计数器总和。预期结果是:

100|0|3|0
103|0|0|2
104|0|0|3

请注意,结果最后一行的计数为3而不是4,因为结果不应包含来自feature3行的信息。

我尝试将GROUP BY和HAVING结合起来,但没有幸运,因为它具有OR的效果,而不是AND。对于具有相同fkey的不同行,挑战似乎是具有AND行为。

SELECT ...
...
GROUP BY fkey
HAVING feature in ('feature1', 'feature2')

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用子查询最简单,然后可以使用AND:

SELECT fkey,
       SUM(count1),
       SUM(count2),
       SUM(count3)
FROM MyTable
WHERE fkey IN (SELECT DISTINCT fkey
               FROM MyTable
               WHERE feature = 'feature1')
  AND fkey IN (SELECT DISTINCT fkey
               FROM MyTable
               WHERE feature = 'feature2')
GROUP BY fkey

或者,使用单个compound subquery

SELECT fkey,
       SUM(count1),
       SUM(count2),
       SUM(count3)
FROM MyTable
WHERE fkey IN (SELECT fkey
               FROM MyTable
               WHERE feature = 'feature1'
               INTERSECT
               SELECT fkey
               FROM MyTable
               WHERE feature = 'feature2')
GROUP BY fkey