首頁 > 後端開發 > 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板