2016-11-26 28 views
-1

我有這樣計數年齡具有明顯在MySQL

PersonID Gender Age CreatedDate 
================================ 
1   M  32 10/09/2011 
2   F  33 10/09/2011 
2   F  33 10/11/2011 
1   M  32 10/11/2011 
3   F  33 10/11/2011 

我想找到性別的創建日期計數按年齡組有一個表,年齡範圍爲30-34和獲取的人是明顯。

所需的輸出應該是這樣的:

Gender AgeRange CreatedDate CountResult 
================================ 
M  30_34 10/09/2011 1 
F  30_34 10/09/2011 1 
F  30_34 10/11/2011 1 

所以,我想這一點,但couldtn幫助:

SELECT t.Gender,'30_34' AS AgeRange,t.CreatedDate, 
     SUM(CASE WHEN t.Age BETWEEN 30 AND 34 THEN 1 ELSE 0 END) AS CountResult, 
FROM (
SELECT DISTINCT PersonID,Gender,Age,CreatedDate 
FROM MyTable 
GROUP PersonID,Gender,Age,CreatedDate 
HAVING COUNT(PersonID)=1 
) t 

我能爲解決做什麼?

感謝

+0

你存儲的年齡嗎?這些人是否已經死亡? – Strawberry

+0

讓我們面對現實;這是一個糟糕的例子。 – Strawberry

回答

0

如果你想如果存在mytable的每PERSONID這個最早的創建日期可能會做 DROP TABLE;

create table mytable(PersonID int, Gender varchar(1),Age int, CreatedDate date); 
insert into mytable values 
(1 ,  'M',  32 , '2011-09-10'), 
(2 ,  'F',  33 , '2011-09-10'), 
(2 ,  'F',  33 , '2011-11-10'), 
(1 ,  'M',  32 , '2011-11-10'), 
(3 ,  'F',  33 , '2011-11-10'); 


select mt.gender, 

     mt.createddate, 
     sum(case when mt.age between 32 and 34 then 1 else 0 end) as Age32to34 

from mytable mt 
where createddate = (select min(mt1.createddate) from mytable mt1 where mt1.personid = mt.personid) 
group by gender,mt.createddate 
0

你似乎想:​​

SELECT t.Gender, '30_34' AS AgeRange, t.CreatedDate, 
     COUNT(DISTINCT t.PersonId) AS CountResult 
FROM MyTable 
WHERE t.Age BETWEEN 30 AND 34 
GROUP BY t.Gender, t.CreatedDate; 
+1

從哪裏來? – kodcu

+0

另外我用sum只用一個sql查詢原因得到其他年齡範圍0_4,5_9,10_14等。 – kodcu

+0

@kodcu。 。 。只能回答你提出的問題。你應該問*另一個問題,如果你想要更多的年齡段 - 這一個很清楚,已經有答案。如果你改變了這個問題,你可能會使可以畫下來的答案失效。 –

0

如何:

SELECT 
    Gender 
    , '30_34' AS AgeRange 
    , CreatedDate 
    , COUNT(*) AS CountResult 
FROM MyTable A 
JOIN (
    SELECT PersonID, MIN(CreatedDate) MinCreatedDate 
    FROM MyTable GROUP BY PersonID 
) B ON B.PersonID = A.PersonID AND B.MinCreatedDate = A.CreatedDate 
WHERE Age BETWEEN 30 AND 34 
GROUP BY Gender, CreatedDate 
ORDER BY CreatedDate, Gender DESC