0

我有这样的表结构:

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 中可行吗?

4

2 回答 2

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
于 2013-01-11T03:37:53.840 回答
0

从字面上看,您需要的一切都在此页面上

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

于 2013-01-11T03:32:54.690 回答