PHP mysql在2个日期之间得到减法

时间:2013-01-11 03:26:05

标签: php mysql

我有这样的表结构:

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中使用吗?

2 个答案:

答案 0 :(得分:3)

这个怎么样? (不太清楚你想要实现的目标......)请求评论。

代码:

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的评论进行编辑:

请注意,我在示例表中添加了额外的少量记录以触发条件。

代码2:

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

答案 1 :(得分:0)