2

我有一个包含这些字段的表:

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

所以,对于所有用户。

我可以遍历用户名,但觉得这不是最好的方法。

4

1 回答 1

2

尝试HAVING Username = 'demo@mybusiness.com'从你的 sql 中删除子句

于 2013-03-27T06:55:10.500 回答