2015-04-13 70 views
1

這裏我SQL結構的例子計數SQL結果:取決於兩行

magazines 
    magazines.id 
    magazines.templateId 
    magazines.userId 

我想算的次數,用戶已經使用特定的模板ID。

考慮3個模板id:100,101和102並考慮5個用戶(10,20,30,40,50)。這裏是SQL數據的一個例子:

magazines 
    1, 100, 10 
    2, 100, 20 
    3, 100, 30 

在這裏,3個不同的用戶有模板#100。但查詢的結果應該是[100 = 1],因爲它是不同的用戶。另一方面,如果我有:

magazines 
    1, 100, 10 
    2, 100, 10 

我應該有templateId [100 = 2]。

我用GROUP BY和UNIQUE嘗試了多個查詢,結果是完全錯誤的。如果有人能幫忙,謝謝。

回答

0

如果希望用戶使用模板的最大次數:

select templateid, userid, count(*) 
from magazines m 
where temploateid = X 
group by templateid, userid 
order by count(*) desc 
limit 1; 

編輯:

你可以得到你想要的東西通過聚合兩次:

select templateid, cnt, count(*) as numUsers 
from (select templateid, userid, count(*) as cnt 
     from magazines m 
     where temploateid = X 
     group by templateid, userid 
    ) tu 
group by templateid, cnt 
order by templateid, cnt; 
+0

謝謝!這是一個很好的賽道。事實上,我需要使用我的模板。模板#1,曾經使用過一次= X個用戶,使用過兩次= X個用戶等等。是否有可能更新查詢?謝謝。 – Michael

0

這將爲您提供每個用戶使用特定模板的次數:

SELECT 
    templateId, 
    userId, 
    COUNT(id) as cnt 
FROM 
    Magazines GROUP BY templateId, userId 

如果你的表有下列數據:

(1, 100, 10), 
    (2, 100, 10), 
    (3, 100, 20), 
    (4, 100, 30) 

然後你設置的結果將是:

templateId userId cnt 
100   10  2 
100   20  1 
100   30  1