For the same table, use SQL to query the difference between today and yesterday, and then sort them. how can this problem be solved?

Source: Internet
Author: User
I am using the leftjoin table, but the result does not seem to be the same as that of SELECT {code ...}.

I use left join to join the table itself, but the result does not seem to be correct.

SELECT

            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

Reply content:

What is quick writing?

I use left join to join the table itself, but the result does not seem to be correct.

SELECT

            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

Assume that the following data table is available:tbl

Uid S Date
1 5 2016-08-31
2 3 2016-08-31
3 7 2016-08-31
1 2
2 5
4 4

Run

SELECT  today.uid,  today.s - IFNULL(yesterday.s, 0) AS diffFROM  (SELECT uid, SUM(s) AS s FROM tbl WHERE date='2016-08-31' GROUP BY uid) AS todayLEFT OUTER JOIN  (SELECT uid, SUM(s) AS s FROM tbl WHERE date='2016-08-30' GROUP BY uid) AS yesterdayUSING (uid)ORDER BY diff DESC;

Result

Uid Diff
3 7
1 3
2 -2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.