我如何在SQL中聚合它

时间:2013-03-27 06:47:28

标签: 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 = '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

所以,对所有用户来说。

我可以遍历用户名,但觉得这不是最佳方式。

1 个答案:

答案 0 :(得分:2)

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