2009-02-22 49 views
4

好吧,我一直在努力,现在解决这个约2小时...请指教:使用复杂的SQL查询覆盖百分比...?

表:

PROFILE [id (int), name (varchar), ...] 
SKILL [id (int), id_profile (int), id_app (int), lvl (int), ...] 
APP  [id (int), ...] 

拉特基本上可以从0到3

我试图获得这个特定的统计数据: “至少有两个拥有2或更高技能的人所覆盖的应用的百分比是多少?”

非常感谢

回答

4
SELECT AVG(covered) 
FROM (
    SELECT CASE WHEN COUNT(*) >= 2 THEN 1 ELSE 0 END AS covered 
    FROM app a 
    LEFT JOIN skill s ON (s.id_app = a.id AND s.lvl >= 2) 
    GROUP BY a.id 
) 

MySQL更有效的方式:

SELECT AVG 
     (
     IFNULL 
     (
      (
      SELECT 1 
      FROM skill s 
      WHERE s.id_app = a.id 
      AND s.lvl >= 2 
      LIMIT 1, 1 
      ), 0 
     ) 
     ) 
FROM app a 

这会停止,因为它找到每个app第二熟练person一旦计数。

如果你有几个app但很多person的有效率。

+0

很好!我从来没有想过用平均水平。 – Rory 2009-02-23 00:18:08

-1
SELECT SUM(CASE lvl WHEN 3 THEN 1 WHEN 2 THEN 1 ELSE 0 END)/SUM(1) FROM SKILL 

如果你的数据库中有一个的if/then功能的CASE而是使用。例如,在MySQL:

SELECT SUM(IF(lvl >= 2, 1, 0))/SUM(1) FROM SKILL 
+0

这个计数技能而不是应用程序。 – Rory 2009-02-23 00:12:45

0

未经测试

select convert(float,count(*))/(select count(*) from app) as percentage 
from (
    select count(*) as number 
    from skill 
    where lvl >= 2 
    group by id_app) t 
where t.number >= 2 
-1

我不知道这是比任何tvanfosson的回答是好还是坏,但在这里它是无论如何:

SELECT convert(float, count(*))/(Select COUNT(id) FROM APP) AS percentage 
FROM APP INNER JOIN SKILL ON APP.id = SKILL.id 
WHERE (
    SELECT COUNT(id) 
    FROM SKILL AS Skill2 WHERE Skill2.id_app = APP.id and lvl >= 2 
) >= 2 
+0

你内心的加入技巧将意味着你不止一次地计算应用程序。您只需计算一次合格的应用程序。 – Rory 2009-02-23 00:14:37

0

逻辑是:百分比= 100 *(感兴趣的应用的数量)/(应用的总数)

select 'percentage' = 
-- 100 times 
    (cast(100 as float) * 
-- number of apps of interest 
    (select count(id_app) 
    from (select id_app, count(*) as skilled_count 
      from skill 
      where lvl >= 2 
      group by id_app 
      having count(*) >= 2) app_counts) 
-- divided by total number of apps 
/(select count(*) from app) 

转换为浮点数是需要的,所以sql不只是做整数算术。