SQL Server 2008:Select在一个月内返回多个结果,而不是每个用户1个

时间:2013-07-22 14:42:12

标签: sql sql-server-2008

我的查询有问题,我希望它将结果集返回到Year = 2013,Month = 1但是每个用户每个月只有一行,我认为这个月的登录时间已合计问题在于我的分组:

SELECT  YEAR(UP_Date) AS 'Year',
        MONTH(UP_Date) AS 'Month',
        SUM(ISNULL(UP_UserID,0)) AS UserID,
        U_UserName AS UserName,
        UP_AveCallTime AS AveCallTime,
        UP_TotCallTime AS TotCallTime,
        CAST(DATEDIFF(DAY,UP_LogOn, UP_LogOff) AS varchar) + ':' +
        CAST(DATEDIFF(HOUR,UP_LogOn, UP_LogOff) AS varchar) + ':' +
        CAST(DATEDIFF(MINUTE,UP_LogOn,UP_LogOff) AS varchar) AS [HoursOfMonth]

FROM [RPT_User_Performance_Data_cus]
INNER JOIN Users us ON
    UP_UserID = us.ID

GROUP BY Year(UP_Date), MONTH(UP_Date), UP_AveCallTime, UP_TotCallTime, U_UserName, UP_LogOn, UP_LogOff

------Result I Get----------------------------
Year    Month   UserID  UserName    AveCallTime TotCallTime HoursOfMonth
2013    6   18552   BossJobs    NULL               NULL           0:0:4
2013    6   18552   BossJobs    NULL               NULL           0:0:02
2013    6   18552   BossJobs    NULL               NULL           0:3:21
2013    6   18552   BossJobs    NULL               NULL           0:5:01
2013    6   18552   BossJobs    NULL               NULL           NULL
2013    6   18553   KingGates   NULL               NULL           0:0:2
2013    6   18553   KingGates   NULL               NULL           0:1:31

-------Instead of ---------------------
Year    Month   UserID  UserName    AveCallTime TotCallTime HoursOfMonth
2013    6   18552   BossJobs    NULL               NULL            0:5:24
2013    6   18553   KingGates   NULL               NULL            0:1:33

2 个答案:

答案 0 :(得分:1)

如果我能理解您的查询,

您可以按照UP_AveCallTime, UP_TotCallTime, U_UserName, UP_LogOn, UP_LogOff之类的内容进行分组,因此请将其从group by

中删除

对于AveCallTime,TotCallTime,HoursOfMonth,您需要使用SUMAVG,具体取决于您的逻辑

答案 1 :(得分:0)

尝试这样的事情:

SELECT  YEAR(UP_Date) AS 'Year',
        MONTH(UP_Date) AS 'Month',
        MAX(ISNULL(UP_UserID,0)) AS UserID,
        U_UserName AS UserName,
        AVG(UP_AveCallTime) AS AveCallTime,
        SUM(UP_TotCallTime) AS TotCallTime,
        CAST(SUM(DATEDIFF(DAY,UP_LogOn, UP_LogOff)) AS varchar) + ':' +
        CAST(SUM(DATEDIFF(HOUR,UP_LogOn, UP_LogOff)) AS varchar) + ':' +
        CAST(SUM(DATEDIFF(MINUTE,UP_LogOn,UP_LogOff)) AS varchar) AS [HoursOfMonth]
FROM [RPT_User_Performance_Data_cus]
INNER JOIN Users us ON UP_UserID = us.ID
GROUP BY Year(UP_Date), MONTH(UP_Date), U_UserName

不确定获取[HoursOfMonth]的逻辑。您可能需要调整它或更好地解释。