SQL获得独特的月份组合

时间:2011-01-04 12:27:08

标签: sql unique distinct

SELECT     MONTH(sessionStart) AS Expr1, YEAR(sessionStart) AS Expr2
FROM         tblStatSessions
WHERE     (projectID = 187)
GROUP BY sessionStart

返回:

  

11 | 2010

     

11 | 2010

     

11 | 2010

     

12 | 2010

     

12 | 2010

但我需要它只返回一次实例,IE:

  

11 | 2010

     

12 | 2010

如果这是有道理的!

2 个答案:

答案 0 :(得分:5)

以下内容应该是您想要的:

SELECT     MONTH(sessionStart) AS Expr1, YEAR(sessionStart) AS Expr2
FROM         tblStatSessions
WHERE     (projectID = 187)
GROUP BY MONTH(sessionStart), YEAR(sessionStart)

通常,您需要group by您选择的每个非聚合列。某些DBMS(例如Oracle)强制执行此操作,即不这样做会导致错误而不是“奇怪”的查询执行。

答案 1 :(得分:0)

尝试:

SELECT     MONTH(sessionStart) AS Expr1, YEAR(sessionStart) AS Expr2
FROM         tblStatSessions
WHERE     (projectID = 187)
GROUP BY Expr1