首页 > 后端开发 > php教程 > 同一个表,用sql查询今天和昨天的差值,然后排序,要怎么做

同一个表,用sql查询今天和昨天的差值,然后排序,要怎么做

WBOY
发布: 2016-09-01 00:20:19
原创
1880 人浏览过

比较快的写法是什么

我现在用left join 这个表本身,但是结果好像不对

SELECT

<code>            table.id ,SUM(table.s-yestoday.a) as sum
            FROM table
            LEFT JOIN table yestoday
            ON yestoday.uid = wy_appdata.uid
            WHERE table.year = '.$year.' AND table.month = '.$month.' AND table.day = '.$day.' AND yestoday.year = '.$bre_data['year'] .' AND yestoday.month ='.$bre_data['month'] .' AND yestoday.day = '.$bre_data['day'] .'
            GROUP BY table.uid
            ORDER BY sum DESC</code>
登录后复制
登录后复制

回复内容:

比较快的写法是什么

我现在用left join 这个表本身,但是结果好像不对

SELECT

<code>            table.id ,SUM(table.s-yestoday.a) as sum
            FROM table
            LEFT JOIN table yestoday
            ON yestoday.uid = wy_appdata.uid
            WHERE table.year = '.$year.' AND table.month = '.$month.' AND table.day = '.$day.' AND yestoday.year = '.$bre_data['year'] .' AND yestoday.month ='.$bre_data['month'] .' AND yestoday.day = '.$bre_data['day'] .'
            GROUP BY table.uid
            ORDER BY sum DESC</code>
登录后复制
登录后复制

假设有如下数据表tbl

uid s date
1 5 2016-08-31
2 3 2016-08-31
3 7 2016-08-31
1 2 2016-08-30
2 5 2016-08-30
4 4 2016-08-30

运行

<code class="sql">SELECT
  today.uid,
  today.s - IFNULL(yesterday.s, 0) AS diff
FROM
  (SELECT uid, SUM(s) AS s FROM tbl WHERE date='2016-08-31' GROUP BY uid) AS today
LEFT OUTER JOIN
  (SELECT uid, SUM(s) AS s FROM tbl WHERE date='2016-08-30' GROUP BY uid) AS yesterday
USING (uid)
ORDER BY diff DESC;</code>
登录后复制

结果

uid diff
3 7
1 3
2 -2
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板