これらのフィールドを含むテーブルがあります。
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 = 'demo@mybusiness.com'
結果は次のようになります。
> Username Year Month LoginCount YearMonth MonthStart
> demo@mybusiness.com 2010 February 1 20102 2010-02-01 00:00:00.000
> demo@mybusiness.com 2010 June 1 20106 2010-06-01 00:00:00.000
> demo@mybusiness.com 2011 November 1 201111 2011-11-01 00:00:00.000
> demo@mybusiness.com 2012 April 115 20124 2012-04-01 00:00:00.000
> demo@mybusiness.com 2012 January 1 20121 2012-01-01 00:00:00.000
この結果を取得したい
> Username Year Month LoginCount YearMonth MonthStart
> demo@mybusiness.com 2010 February 1 20102 2010-02-01 00:00:00.000
> demo@mybusiness.com 2010 June 1 20106 2010-06-01 00:00:00.000
> demo@mybusiness.com 2011 November 1 201111 2011-11-01 00:00:00.000
> demo@mybusiness.com 2012 April 115 20124 2012-04-01 00:00:00.000
> demo@mybusiness.com 2012 January 1 20121 2012-01-01 00:00:00.000 >
> user@mybusiness.com 2010 February 3 20102 2010-02-01 00:00:00.000
> user@mybusiness.com 2010 June 2 20106 2010-06-01 00:00:00.000
> user@mybusiness.com 2011 November 0 201111 2011-11-01 00:00:00.000
> user@mybusiness.com 2012 April 190 20124 2012-04-01 00:00:00.000
> user@mybusiness.com 2012 January 6 20121 2012-01-01 00:00:00.000
したがって、すべてのユーザーにとって。
ユーザー名をループすることはできますが、それが最善の方法ではないと感じています。