2014-07-16 55 views
1
我使用MySQL

是我的表名爲npstable獨特的人得分月

pk id | score | personid | date 
--------------------------------------- 
435 | 4 | 33  | 2012-01-05 
436 | 10 | 78  | 2012-01-21 
437 | 5 | 22  | 2012-05-11 
438 | 2 | 33  | 2012-01-22 
439 | 10 | 22  | 2012-05-25 
440 | 4 | 33  | 2012-02-05 

我想這些人的得分一樣,我想

pk id | score | personid | date 
--------------------------------------- 
435 | 4 | 33  | 2012-01-05 
436 | 10 | 78  | 2012-01-21 
437 | 10 | 22  | 2012-05-25 
440 | 4 | 33  | 2012-02-05 
誰沒有在同一個月得分

我已經使用查詢與我這樣的其他要求

「select * from npstable where date_created> ='2012-01-01'AND date_created < ='2012-06-05'AND AND BETWEEN 0 A ND 10;「

任何想法如何使選擇查詢,可以生成我所需的報告。

+0

使用SELECT DISTINCT(得分)版本,看看這篇文章 - > http://stackoverflow.com/questions/5967130/mysql-select-one-column-distinct-with-corresponding-other-columns – SerhatCan

+1

重複http://stackoverflow.com/questions/16979136/mysql- select-distinct-records-from-latest-dates-only – ahruss

+0

檢查ou你的需求輸出。你認爲最後一行是正確的嗎? –

回答

0

此查詢選擇每月每最早記錄PERSONID

select t1.* 
from npstable t1 
join (
    select 
     personid, year(date) my_year, 
     month(date) my_month, min(date) min_date 
    from npstable t2 
    group by person_id, my_year, my_month 
) t2 join on year(t1.date) = t2.my_year 
      and month(t1.date) = t2.my_month 
      and t1.date = t2.min_date 
      and t1.personid = t2.personid 

另一種選擇,每月每PERSONID最低ID行

select t1.* 
from npstable t1 
where id in (select 
    min(id) from npstable t2 
    group by personid, month(date), year(date) 
)