2013-03-27 49 views
2

我有一個表,這些字段:如何聚集在SQL中

UserLogonAuditID, Username, LogonDate FROM dbo.UserLogonAudit 

與此查詢:

SELECT Username , 
     DATEPART(Year, LogonDate) [Year] , 
     DATENAME(MONTH, LogonDate) [Month] , 
     COUNT(1) [LoginCount] , 
     CAST(DATEPART(Year, LogonDate) AS VARCHAR(4)) 
     + CAST(DATEPART(Month, LogonDate) AS VARCHAR(2)) AS [YearMonth] , 
     CAST(CAST(DATEPART(Year, LogonDate) AS VARCHAR(4)) + '-' 
     + CAST(DATEPART(Month, LogonDate) AS VARCHAR(2)) + '-1' AS datetime) AS [MonthStart] 
FROM UserLogonAudit 
GROUP BY DATEPART(Year, LogonDate) , 
     DATENAME(Month, LogonDate) , 
     DATEPART(Month, LogonDate) , 
     Username 
HAVING Username = '[email protected]' 

結果在此:

> Username   Year  Month LoginCount YearMonth MonthStart 
> [email protected] 2010 February 1 20102 2010-02-01 00:00:00.000 
> [email protected] 2010 June  1 20106 2010-06-01 00:00:00.000 
> [email protected] 2011 November 1 201111 2011-11-01 00:00:00.000 
> [email protected] 2012 April  115 20124 2012-04-01 00:00:00.000 
> [email protected] 2012 January  1 20121 2012-01-01 00:00:00.000 

我想要得到這個結果

> Username   Year  Month LoginCount YearMonth MonthStart 
> [email protected] 2010 February 1 20102 2010-02-01 00:00:00.000 
> [email protected] 2010 June  1 20106 2010-06-01 00:00:00.000 
> [email protected] 2011 November 1 201111 2011-11-01 00:00:00.000 
> [email protected] 2012 April  115 20124 2012-04-01 00:00:00.000 
> [email protected] 2012 January  1 20121 2012-01-01 00:00:00.000 > 
> [email protected] 2010 February 3 20102 2010-02-01 00:00:00.000 
> [email protected] 2010 June  2 20106 2010-06-01 00:00:00.000 
> [email protected] 2011 November 0 201111 2011-11-01 00:00:00.000 
> [email protected] 2012 April  190 20124 2012-04-01 00:00:00.000 
> [email protected] 2012 January  6 20121 2012-01-01 00:00:00.000 

因此,對於所有用戶。

我可以通過用戶名循環,但覺得這不是最好的方法。

回答

2

嘗試從SQL

+1

刪除HAVING Username = '[email protected]'條款哇咔咔。我現在不覺得很傻!我想我只能說缺乏睡眠是我的防守! – callisto 2013-03-27 06:58:01