同时获取同一表中两列的计数而未显示第二列的正确计数

时间:2013-09-04 09:36:45

标签: sql-server

我的存储过程如下:

ALTER procedure [dbo].[Driverperformance] 
 @Ecode nvarchar(50),  
 @startdate datetime,
 @enddate datetime  as
begin  
    SELECT e.Ecode,CAST(q.dtime AS DATE) as Date , 
           e.Ename, 
           count(q.Ecode) CntEcode ,
           count(q.DelEcode) CntDelEcode
    FROM EmployeeMaster_tbl e 
     inner JOIN Transaction_tbl q  
      ON e.Ecode = q.Ecode 
    where q.Ecode=@Ecode
     and dtime between '' + @startdate +'' and ''+@enddate+'' 
    group by e.Ecode, e.Ename, CAST(q.dtime AS date) 
    ORDER BY CAST(q.dtime AS date)--e.Ecode DESC
end

我传递了这样的参数: @Ecode = 'E003' @startdate = '2013-09-03', @enddate = '2013-09-03'

enter image description here

我这样出去了:但是cntDelEcode出错了。(我没有得到正确的DelEcode计数)所以我必须在存储过程中改变它)

用于检查CntEcode的计数i worte查询如下:

select * from Transaction_tbl where dtime >='2013-09-03 00:00:00.000' and dtime <='2013-09-03 23:59:59.000' and Ecode='E003' 

。现在我得到27行。所以我明白我的cntEcode计数是核心。 用于检查CntDelEcode的计数我会像这样查询:

select * from Transaction_tbl where dtime >='2013-09-03 00:00:00.000' and dtime <='2013-09-03 23:59:59.000' and DelEcode='E003'

现在我得到了35行..但是在执行我的存储过程时,我只得到23行插入获得35行..我的存储过程出错了?请帮我看看

1 个答案:

答案 0 :(得分:0)

在您获得35行的查询中,您计算​​DelECode='E0003'

所在的行

与上述查询不同的查询。难怪结果不同。

您可以将查询更改为

SELECT e.Ecode,CAST(q.dtime AS DATE) as Date , 
       e.Ename, 
       count(q.Ecode) CntEcode ,
       (select count(*) from Transaction_tbl 
               where q.Ecode=@Ecode
               and dtime between @startdate and @enddate) CntDelEcode
FROM EmployeeMaster_tbl e 
     ...