我有一张这样的表:
Transactid dtime Ecode DelEcode
1 2013-08-01 E003 null
2 2013-08-01 E003 E003
3 2013-08-02 E001
4 2013-08-02 E001
我希望Ecode
和DelEcode
计算特定日期和Ecode
的名称。现在,如果Ecode
具有Ecode
和DelEcode
这样的存储过程,我会得到答案:
ALTER PROCEDURE [dbo].[Driverperformanceforalldriver] @startdate DATETIME,
@enddate DATETIME AS BEGIN DECLARE @date1 DATETIME = CONVERT(DATETIME, @startdate + ' 00:01:00.000', 120);
DECLARE @date2 DATETIME = CONVERT(DATETIME, @enddate + ' 23:23:59.000', 120) ;
;
WITH cnt AS
(SELECT e.ecode,
Cast(q.dtime AS DATE) AS Date,
e.ename,
Count(q.ecode) cntEcode
FROM employeemaster_tbl e
JOIN transaction_tbl q ON e.ecode = q.ecode
WHERE q.ecode in
(SELECT e.Ecode
FROM dbo.EmployeeMaster_tbl e
WHERE e.gid NOT IN
(SELECT did
FROM dbo.Designation_tbl d
WHERE d.Dname ='Driver'))
AND dtime >=''+ @date1 + ''
AND dtime <= '' + @date2 + ''
GROUP BY e.ecode,
e.ename,
Cast(q.dtime AS DATE)),
del AS
(SELECT e.ecode,
Cast(q.dtime AS DATE) AS Date,
e.ename,
Count(q.delecode) CntDelEcode
FROM employeemaster_tbl e
JOIN transaction_tbl q ON e.ecode = q.delecode
WHERE q.delecode IN
(SELECT e.Ecode
FROM dbo.EmployeeMaster_tbl e
WHERE e.gid NOT IN
(SELECT did
FROM dbo.Designation_tbl d
WHERE d.Dname ='Driver'))
AND dtime >= '' + @date1 + ''
AND dtime <= '' + @date2 + ''
GROUP BY e.ecode,
e.ename,
Cast(q.dtime AS DATE))
SELECT del.ecode,
del.[Date],
del.ename,
ISNULL(cnt.cntEcode, 0) CntEcode ,
ISNULL(del.CntDelEcode, 0) AS CntDelEcode
FROM cnt FULL
JOIN del ON del.ecode = cnt.ecode
AND del.[Date] = cnt.[Date]
AND del.Ename = cnt.Ename
ORDER BY del.date END
执行后,我得到了这个输出:
Ecode dtime Ename cntEcode CntDelCode
E003 2103-08-01 raheem 2 1
null null null 2 0
如果有任何DelEcode
,那么只显示其他detils(我的意思是E001
中有任何DelEcode
然后正常工作。我的存储过程出了什么问题?
Ecode dtime Ename cntEcode CntDelCode
E003 2103-08-01 raheem 2 1
E001 2103-08-02 jaseem 2 0
答案 0 :(得分:0)
以下是程序的select
部分:
SELECT del.ecode,
del.[Date],
del.ename,
ISNULL(cnt.cntEcode, 0) CntEcode ,
ISNULL(del.CntDelEcode, 0) AS CntDelEcode
FROM cnt FULL JOIN
del
ON del.ecode = cnt.ecode AND del.[Date] = cnt.[Date] AND del.Ename = cnt.Ename;
您正在执行full join
,然后仅从一个表中提取数据。该表中可能没有数据。因此,请使用coalesce()
:
SELECT coalesce(del.ecode, cnt.ecode) as ecode,
coalesce(del.[Date], cnt.[Date]) as [Date],
coalesce(del.ename, cnt.Ename) as Ename,
coalesce(cnt.cntEcode, 0) as CntEcode,
coalesce(del.CntDelEcode, 0) as CntDelEcode
FROM cnt FULL JOIN
del
ON del.ecode = cnt.ecode AND del.[Date] = cnt.[Date] AND del.Ename = cnt.Ename;