2014-02-17 96 views
0

數據庫的簡化版:每組需要多個記錄值分組?

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與特徵1和特徵有關(在現實生活中的功能列表中可以達到10或20)。我也想要功能1和功能2的計數器的總和。預期的結果是:

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

需要注意的是對結果的最後一行的計數是3而不是4的結果不應該包括來自與特點3行信息。

我試圖將GROUP BY和HAVING結合起來,但沒有幸運,因爲它具有OR的效果,而不是AND。對於具有相同fkey的不同行,挑戰似乎具有AND行爲。

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

任何想法?

回答

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 
+0

我選擇了INTERSECT建議,和作品。目前的標題是否適合這個問題? –

相關問題