2011-10-05 72 views
2

我有以下幾列排名CREATED_DATE表1MySQL的SELECT語句應該返回一個唯一的行

我想

SELECT 
    name, 
    rank for latest created_date, 
    latest created_date, 
    difference between rank current created_date & previous date 
FROM 
    table1 

有每人CREATED_DATE人只有一個記錄。

輸出應該是:

Sam 15 2011/10/05 -3 

感謝您的幫助。

+0

我無法找到的差異,這是我做了什麼:SELECT名字,CREATED_DATE,排名 FROM表1 WHERE CREATED_DATE =(SELECT CREATED_DATE FROM表1 ORDER BY created_date DESC LIMIT 1) – Ram

回答

1
SELECT 
    name, 
    rank, 
    created_date, 
    rank - (
    SELECT rank FROM table1 AS bar 
    WHERE bar.created_date < foo.created_date 
    ORDER BY created_date DESC 
    LIMIT 1 
) AS diff 
FROM table1 AS foo 
ORDER BY created_date DESC 
LIMIT 1 

編輯:重讀你的問題,我想你想獲得一個輸出行每人,隨着最後兩個記錄的那個人之間計算得到的差值。如果是這樣,則需要一個稍微複雜的解決方案:

SELECT 
    name, 
    rank, 
    created_date, 
    rank - (
    SELECT rank FROM table1 AS bar 
    WHERE bar.name = foo.name AND bar.created_date < foo.created_date 
    ORDER BY created_date DESC LIMIT 1 
) AS diff 
FROM table1 AS foo 
NATURAL JOIN (
    SELECT name, MAX(created_date) AS created_date FROM table1 
    GROUP BY name 
) AS blah 
+0

我想我還需要在內部SELECT中添加名稱,否則我只能得到第一條記錄,它的排名,日期和差異。應SELECT 名, 秩, CREATED_DATE, 秩 - ( SELECT秩FROM表1 AS酒吧 WHERE bar.created_date Ram

+0

感謝您的幫助! – Ram