SQL Server存储过程问题。从数据库中获取多个结果

时间:2014-04-28 19:08:43

标签: sql sql-server stored-procedures group-by

以下是我的存储过程,用于获取员工列表及其在StartDateEndDate之间的工作时间。

ALTER procedure [dbo].[usp_get_employeehourlyreport]
  @startdate  datetime,
  @enddate datetime
as 
begin
   select * 
   from (
      select 
         (select FullName from Registration 
          where Registration.UserId = UserTime.UserId) Fullname, 
         ISNULL(SUM(HoursWorked), 0) HoursWorked 
      from UserTime 
      where CheckIn between @startdate and @enddate
      group by UserId, CheckIn) tbl
end

我得到的结果是:

   Fullname             HoursWorked
   Antonio Jake         0
   Antonio Jake         0.016666

所以基本上它显示一行额外的小时0.我的数据库中没有任何重复的FullName。

表结构是:

USERTIME

  UserTimeId    int             Unchecked
  UserId        int             Checked
  CheckIn       datetime        Checked
  LoginStatus   nvarchar(50)    Checked
  Day           varchar(50)     Checked
  HoursWorked   float           Checked
  Date          nvarchar(50)    Checked

REGISTRATION

  UserId    int Unchecked
  FullName  varchar(50) Checked

1 个答案:

答案 0 :(得分:1)

尝试这样的事情......

ALTER procedure [dbo].[usp_get_employeehourlyreport]
@startdate  datetime,
@enddate datetime
AS
BEGIN
 SET NOCOUNT ON;

    SELECT R.FullName, ISNULL(SUM(UT.HoursWorked),0) AS Total_Hours 
    FROM Registration R LEFT JOIN USERTIME UT
    ON   R.UserId = UT.UserId                                                                                                                    Fullname ,ISNULL(SUM(HoursWorked),0) HoursWorked from UserTime 
    AND   UT.CheckIn >= @startdate 
    AND   UT.CheckIn <= @enddate
    GROUP BY R.FullName
END