我有这样的表结构:
Id Name Rank Date
-----------------------------------
1 test 1000 2012-1-11
2 test 7000 2012-1-10
3 test2 2000 2012-1-11
4 test2 200 2012-1-10
5 test3 4000 2012-1-10
6 test4 6500 2012-1-11考虑今天的日期是2012-1/11昨天的日期是2012-1/10
在单个查询中,我得到了今天和昨天的每个用户名之间的差异。即昨天有7000个排名,今天有1000个排名。所以结果是6000,类似于test2的-1800。
我需要如下输出:
Name Difference (Orderby the difference Desc)
--------------------
test 6000
test2 -1800如果今天日期或昨天日期的记录不可用,则我们不会使用此记录进行计算。
这在PHP MySQL中是可能的吗?
发布于 2013-01-11 11:37:54
这个怎么样?(不是很清楚你想要达到什么目的。)请发表意见。
代码:
select b.id, b.name, (b.rank-a.rank) diff
from t1 a
left join t1 b
on b.date < a.date
and b.name = a.name
having not diff is null
;结果:
ID NAME DIFF
2 test 6000
4 test2 -1800根据OP的评论进行编辑:
请注意,我已经向示例表中添加了额外的几条记录,用于触发条件。
Code2:
select b.id, b.name,b.rank AS New,
b.Date new_date,
a.Rank as Old, a.date as old_date,
(b.rank-a.rank) diff
from t1 a
left join t1 b
on b.name = a.name
where b.date > a.date and b.date <= Now()
and datediff(b.date, a.date) = 1
having not diff is null and diff <> 0
order by diff desc
;结果:
ID NAME NEW NEW_DATE OLD OLD_DATE DIFF
3 test 8000 January, 12 2012 1000 January, 11 2012 7000
4 test2 2000 January, 11 2012 200 January, 10 2012 1800
1 test 1000 January, 11 2012 7000 January, 10 2012 -6000发布于 2013-01-11 11:32:55
https://stackoverflow.com/questions/14271177
复制相似问题