Home > Backend Development > PHP Tutorial > In the same table, use SQL to query the difference between today and yesterday, and then sort it. How to do it?

In the same table, use SQL to query the difference between today and yesterday, and then sort it. How to do it?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-09-01 00:20:19
Original
1895 people have browsed it

What is the faster way to write?

I am now using left join on the table itself, but the result seems wrong

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>
Copy after login
Copy after login

Reply content:

What is the faster way to write?

I am now using left join on the table itself, but the result seems wrong

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>
Copy after login
Copy after login

Suppose there is the following data tabletbl

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

Run

<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>
Copy after login

Results

uid diff
3 7
1 3
2 -2
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template