MYSQL中的某位用户如何将日期条目中的用户百分比与其他日期条目和得分进行比较,从而有效地将用户百分比从一个日期返回到另一个日期?
我一直试图绕过这个问题几天,但我的想法已经用完了,觉得我的sql知识有限。不确定我是否应该使用连接或子查询? MYSQL表包含3个字段,名称,分数和日期。
表:userData
name score date
joe 5 2014-01-01
bob 10 2014-01-01
joe 15 2014-01-08
bob 12 2014-01-08
返回了查询提示
user %inc last date
joe 33% 2014-01-08
bob 17% 2014-01-08
似乎这样一个简单的函数,一个数据库可以服务但试图理解这是我的掌握?
答案 0 :(得分:0)
您需要使用SUBQUERIES
。类似的东西:
SELECT name,
((SELECT score
FROM userData as u2
WHERE u2.name = u1.name
ORDER BY date desc
LIMIT 1
)
/
(
SELECT score
FROM userData as u3
WHERE u3.name = u1.name
ORDER BY date desc
LIMIT 1,1
)
* 100.0
) as inc_perc,
max(date) as last_date
FROM userData as u1
GROUP BY name
答案 1 :(得分:0)
简单解决方案假设%Inc列的公式=总计/总和* 100
select name,total/sum * 100, date from (
select name,sum(score) as total,count(*) as num,date from table group by name
)as resultTable
答案 2 :(得分:0)
select a.name as [user],(cast(cast(b.score as float)-a.score as float)/cast(a.score as float))*100 as '% Inc',b.[date] as lastdate
from userdata a inner join userdata b on a.name = b.name and a.date < b.date
我猜您正在寻找与过去日期相比得分增加百分比
答案 3 :(得分:0)
另一种方式(注意,我有另一个结果。基于名称&#34; percinc&#34;,百分比增加,我在我眼中正确计算。如果你想要你的结果,只需用{计算它} {1}}):
示例数据:
t1.score / t2.score * 100
查询:
CREATE TABLE t
(`name` varchar(3), `score` int, `date` varchar(10))
;
INSERT INTO t
(`name`, `score`, `date`)
VALUES
('joe', 5, '2014-01-01'),
('bob', 10, '2014-01-01'),
('joe', 15, '2014-01-08'),
('bob', 12, '2014-01-08')
;
结果:
select
t1.name,
t1.score first_score,
t1.date first_date,
t2.score last_score,
t2.date last_date,
t2.score / t1.score * 100 percinc
from
t t1
join t t2 on t1.name = t2.name
where
t1.date = (select min(date) from t where t.name = t1.name)
and t2.date = (select max(date) from t where t.name = t1.name);