如何创建分组年份的查询

时间:2014-05-22 03:31:51

标签: mysql sql group-by

我有这个问题:

SELECT Count(tblpeople.PersonID) AS Total, 
     YEAR(CURRENT_TIMESTAMP) - YEAR(tblmembership.MemberSince) AS YearsMember   
FROM tblmembership 
   INNER JOIN tblpeople ON tblmembership.PersonID = tblpeople.PersonID
WHERE 
      tblpeople.MemSTATUS = 'Back from VPM' 
  OR  tblpeople.MemSTATUS = 'Sent To VPM 2' 
  OR  tblpeople.MemSTATUS = 'Sent To VPM 1' 
  OR  tblpeople.MemSTATUS = 'Back from VPM' 
  OR  tblpeople.MemSTATUS = 'Renewal'
  OR  tblpeople.MemSTATUS = 'Active Member'
GROUP BY YearsMember 
HAVING YearsMember
ORDER BY YearsMember

它取决于人们成为会员的年份。

What has me stumped is the boss wants it broken down by:
0 - 2, 
3 -5, 
6 - 10, 
11 - 20, 
>20

所以每个都很重要。我无法弄清楚如何做到这一点,虽然我确定有办法!

我可以把它带到excel并手动分组计数,但希望一次性完成。

由于

2 个答案:

答案 0 :(得分:0)

表达式http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm

时使用案例
case when years between 0 and 2 then ... else ...

答案 1 :(得分:0)

使用IN代替所有OR语句。然后使用CASE语句对结果进行分组:

SELECT Count(tblpeople.PersonID) AS Total, 
    CASE 
      WHEN YEAR(CURRENT_TIMESTAMP) - YEAR(tblmembership.MemberSince) BETWEEN 0 AND 2 
      THEN '0-2' 
      WHEN YEAR(CURRENT_TIMESTAMP) - YEAR(tblmembership.MemberSince) BETWEEN 3 AND 5 
      THEN '3-5', 
      ...
      WHEN YEAR(CURRENT_TIMESTAMP) - YEAR(tblmembership.MemberSince) > 20 
      THEN '>20'
    END AS YearsMember 
FROM tblmembership 
    INNER JOIN tblpeople ON tblmembership.PersonID = tblpeople.PersonID
WHERE tblpeople.MemSTATUS IN ( 'Back from VPM', 'Sent To VPM 2', 'Sent To VPM 1', 
                               'Back from VPM', 'Renewal', 'Active Member')
GROUP BY YearsMember 
ORDER BY YearsMember