我想要查询的是获取hoursbilled
的计数。我想首先检查#worked
,但如果该表中不存在数据,我想从#workschedule
中提取数据。
我的问题似乎是将我的数据合计两次,即如果它在两个表中都存在,则计算两次hoursbilled
。这在我的测试数据上工作正常,但当我将其推出到我的生产数据时会出现此问题。这是一个不正确的连接,还是错误的查询设置?我需要做什么才能准确计算hoursbilled
?
基本上我的查询尝试的是:
#worked
中存在日期,请使用该表中的hoursbilled
hoursbilled
#workschedule
Create Table #workschedule
(
caldate date
,isworkday varchar(5)
,hoursbilled int
)
Insert Into #workschedule Values
('01/01/2000', 'yes','3'), ('01/02/2000', 'yes','3'), ('01/03/2000', 'yes','1'),
('01/04/2000', 'no','0'), ('01/05/2000', 'yes','12'), ('01/06/2000', 'no','0')
Create Table #worked
(
d1 date
,hoursbilled int
)
Insert Into #worked Values
('01/01/2000','2'), ('01/02/2000','4')
Declare @begin date, @end date
Set @begin = '01/01/2000'
Set @end = '01/08/2000'
Select
ws.caldate,
case when wk.d1 = ws.caldate then wk.hoursbilled else ws.hoursbilled end
FROM #workschedule ws
Left Join #worked wk
ON ws.caldate = wk.d1
where ws.isworkday = 'Yes'
答案 0 :(得分:0)
@begin和@end根本不在您的查询中使用。很少有问题可能有助于缩小问题范围:
。你有另一个谓词来限制时间吗?
。加入后你会在caldate
汇总吗?
。你在#workschedule和#worked中有重复的条目与'caldate'相同吗?例如。你是否对#workschedule和#worked表的'caldate'有'唯一'约束?
以下是产生双重计数的潜在原因示例:
/*
create database test
use test
-- drop table #workschedule
Create Table #workschedule
(
caldate date
,isworkday varchar(5)
,hoursbilled int
)
Insert Into #workschedule Values
('01/01/2000', 'yes','3'), ('01/02/2000', 'yes','3'), ('01/03/2000', 'yes','1'),
('01/04/2000', 'no','0'), ('01/05/2000', 'yes','12'), ('01/06/2000', 'no','0'),
('01/01/2000', 'yes', '0') -- dup entry
-- drop table #worked
Create Table #worked
(
d1 date
,hoursbilled int
)
Insert Into #worked Values
('01/01/2000','2'), ('01/02/2000','4'),
('01/01/2000', '5') -- dup entry
*/
Declare @begin date, @end date
Set @begin = '01/01/2000'
Set @end = '01/08/2000'
-- Here 2000/01/01 counted duplicated, should only account for 7, but got 14.
--2000-01-01 14
--2000-01-02 4
--2000-01-03 1
--2000-01-05 12
Select
ws.caldate,
sum(
case
when wk.d1 = ws.caldate then wk.hoursbilled
else ws.hoursbilled
end
) hoursBilled
FROM #workschedule ws
Left Join #worked wk
ON ws.caldate = wk.d1
where
ws.isworkday = 'Yes'
and ws.caldate between @begin and @end
group by ws.caldate
order by ws.caldate