好的,我现在一直试图解决这个问题大约2个小时......请告知:
表:
PROFILE [id (int), name (varchar), ...]
SKILL [id (int), id_profile (int), id_app (int), lvl (int), ...]
APP [id (int), ...]
lvl基本上可以从0到3。
我正试图获得这个特定的统计数据: “至少有两个技能为2或更高的人所覆盖的应用程序的百分比是多少?”
非常感谢
答案 0 :(得分: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
一旦找到每个person
的第二位熟练app
,就会停止计算。
如果您有app
个person
但有很多{{1}},则效率很高。
答案 1 :(得分: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
答案 2 :(得分: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 )
需要转换为float,因此sql不只是执行整数运算。
答案 3 :(得分:-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
答案 4 :(得分:-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