Sql加入返回空结果而不接受条件

时间:2018-01-09 06:29:07

标签: sql sql-server

我有4个表,我试图从中获取数据,但我的join语句返回null。我试过full, left and right joins没有成功。下面我提供了我的代码和图表,返回null值的表是ChannelData表。我想在开始和结束日期之间总结Vvalue from this table, when i add the condition that i commented out below i.e.我的查询返回没有结果。我知道我的连接一定有问题,但我已经尝试了一切。此表未正确规范化,我必须按原样使用它:

 DECLARE @bp varchar(4)
DECLARE @priority varchar(2)
DECLARE @startDate datetime
DECLARE @endDate datetime

SET @bp = 1710
SET @priority = 2

SET @endDate = (SELECT EndDate FROM BillingPeriod WHERE BillingPeriodClass_ID = 1 AND CODE = @BP)
SET @startDate = (SELECT EndDate FROM BillingPeriod WHERE BillingPeriodClass_ID = 1 AND CODE = @BP -1 )
SET @startDate = dateadd(minute, 1, @startDate)


SELECT  CGS.Description, SUM(CD.Vvalue) AS P_Val, COUNT(CD.VValue) AS P_Rec, DI.Margin
FROM CGS AS CGS

 FULL JOIN ChannelParameter AS CP ON CP.ID = CGS.ID
 FULL JOIN ChannelData AS CD ON CP.ID = CD.ID 
FULL JOIN DataIntegrity AS DI ON DI.CGS_ID_1 = CGS.ID OR DI.CGS_ID_2 = CGS.ID

WHERE --CD.DDate BETWEEN @startDate AND @endDate AND
    DI.Priority = @priority

 group by CGS.Description, DI.Margin

Click this for Query Result

请参阅以下内容:

Channel Data Table

Channel Parameter Table

我已经将图片附加为链接:这里也就是我的意思是表没有正确规范化它们都有CGS.ID作为原始和外键但这实际上是cgs表中的主键,问题在于我尝试加入DI表我没有得到所有表格的结果:

DECLARE @bp varchar(4)
DECLARE @priority varchar(2)
DECLARE @startDate datetime
DECLARE @endDate datetime

SET @bp = 1710
SET @priority = 2

SET @endDate = (SELECT EndDate FROM BillingPeriod WHERE BillingPeriodClass_ID = 1 AND CODE = @BP)
SET @startDate = (SELECT EndDate FROM BillingPeriod WHERE BillingPeriodClass_ID = 1 AND CODE = @BP -1 )
SET @startDate = dateadd(minute, 1, @startDate)


SELECT  CGS.Description, SUM(CD.Vvalue) AS P_Val, COUNT(CD.VValue) AS P_Rec
FROM CGS AS CGS

 FULL JOIN ChannelParameter AS CP ON CP.ID = CGS.ID
 FULL JOIN ChannelData AS CD ON CP.ID = CD.ID 


WHERE CD.DDate BETWEEN @startDate AND @endDate and CGS.ID = 88


 group by CGS.Description

结果:

       Description                         P_Val         P_Rec

EP 308 12 CONTROL TRF FEEDER NO 1 - Q Exp,    4514.37,   1488

1 个答案:

答案 0 :(得分:0)

问题非常明显,CD.DDate BETWEEN @startDate AND @endDate条件没有匹配的记录。我怀疑@startDate变量可能是null,因为没有返回CODE = @BP -1条件的记录。那么,你会尝试改变这一行吗;

SET @startDate = (SELECT top 1 EndDate FROM BillingPeriod 
WHERE BillingPeriodClass_ID = 1 AND CODE < @BP order by CODE desc)