DB2 Coalesce not returning expected value - sql

I'm trying to coalesce between two last_record values but I'm receiving a null result despite knowing one of the values is non null. When querying these values alone, an expected non-null value is returned though when checked through coalesce I'm receiving null.
Portion of code:
select rds.*,
case when row_num=coalesce(bo.last_record, boa.last_record)
then closing - (rolling_debit - debit) else debit end Aged_Debt
from rolling_debit_sum rds
inner join balance_overflow bo
on rds.client_number = bo.client_number
inner join balance_overflow_aft boa
on rds.client_number = boa.client_number
where row_num >= coalesce(bo.last_record, boa.last_record)
I Know that last_record is not null in at leasat one of two cases, though the query returns null for both. Any ideas what might be the issue here?

The issue was within the join.
An outer join was required rather than inner.

Related

Return 1 instead of 0 when Count(*) result is Null

My code from SQL Server:
SELECT ESTAGIO.SK_ESTAGIO, ISNULL(count(ESTAGIO.SK_ESTAGIO), 0) as how_many
from ESTAGIO
left join ESTAGIARIO
on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
group by
ESTAGIO.SK_ESTAGIO
When "ESTAGIO.SK_ESTAGIO" doesn't exist in the table "ESTAGIARIO" it returns 1 instead of 0, I already tried to use ISNULL(), NULLIF() and COALESCE() and still couldn't find the problem that is making the query above returning 1 when it should be 0.
You are counting the wrong field. Do it like this, taking the field from the outer joined table ESTAGIARIO (not from ESTAGIO):
SELECT ESTAGIO.SK_ESTAGIO, Count(ESTAGIARIO.SK_ESTAGIO) as how_many
from ESTAGIO
left join ESTAGIARIO
on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
group by
ESTAGIO.SK_ESTAGIO
BTW, count can never return null.

SQL Server operating with null value

I'm trying to make an average of two columns that may or not contain in the second one Null values. Can someone help me get an idea of how to make an operation between these values?
select
nib, primeiroTitular, segundoTitular,
((YEAR(GETDATE()) - YEAR(P1.dataNascimento)) +
(YEAR(GETDATE()) - YEAR(P2.dataNascimento)))/2 as média
from
ContasBancarias
left join
Pessoas P1 on P1.bi = ContasBancarias.primeiroTitular
left join
Pessoas P2 on P2.bi = ContasBancarias.segundoTitular
Here is what you can do. I changed the way that you do calculation between the two dates I used the DATEDIFF() function Next time try to indent your code when you ask a question it's easier for the people when they try to read your code.
SELECT nib
, primeiroTitular
, segundoTitular
,(DATEDIFF(YEAR,GETDATE(), CASE
WHEN P1.dataNascimento IS NULL
THEN GETDATE()
ELSE P1.dataNascimento
END )
+ DATEDIFF(YEAR,GETDATE(),CASE
WHEN P2.dataNascimento IS NULL
THEN GETDATE()
ELSE P2.dataNascimento
END) )/2 as média
FROM ContasBancarias
LEFT JOIN Pessoas P1
ON P1.bi = ContasBancarias.primeiroTitular
LEFT JOIN Pessoas P2
ON P2.bi = ContasBancarias.segundoTitular
Assuming only the second column could be NULL try this -
([Column1] + ISNULL(Column2,0))/2 AS [Average]
In the interest of accuracy, I would recommend NOT INCLUDING any NULLs in your equation, since NULL means "don't know the value", "don't know what the value is", or "don't know if this value is relevant at all". To assign a zero value to NULL is to skew the results.
Most accurate results, use the WHERE clause to eliminate any row with NULL from the calculations, or the ISNULL function.

SQL left join gives wrong results

In table A (i.e. Charges) I have my data and in B (i.e gdh) there are mappings.
For some reason my query doesn't show rows without mappings with null value.
Any thoughts?
select a.chargeable_object, a.debitor, a.source_bu, a.target_cc, a.target_bu, b.L5_CLUSTER, sum(a.charge)
from charges a
left join gdh b on a.target_cc = b.department_id
where a.account not like ('H%')
and a.chargeable_object is not null
and a.source_bu in ('301','161','303')
and a.debitor not in ('0315X02', '0961901', '0972023', '0972024',......)
group by a.chargeable_object, a.debitor, a.source_bu, a.target_cc, a.target_bu, b.L5_CLUSTER
It would help to see some example data. Anyhow does the column a.target_cc contains null values? I would expect that those would be filtered out.

COUNT_BIG() returns as 1 even though it should be 0

I have the following query:
SELECT dbo.Enquiries.EnquiryID, COUNT_BIG(dbo.Enquiries.EnquiryID) AS AttachedLines
FROM dbo.Enquiries INNER JOIN
dbo.QuoteLines ON dbo.Enquiries.EnquiryID = dbo.QuoteLines.EnquiryID
GROUP BY dbo.Enquiries.EnquiryID
Some of my enquiries have 0 QuoteLines attached, yet in my View, they return as 1?
Change COUNT_BIG(*) to counting on a column, e.g. COUNT_BIG(SomeColumn) - this will skip NULLs in the column. I assume your actual query is using a LEFT JOIN.
For your situation, you state
Some of my enquiries have 0 QuoteLines attached, yet in my View, they return as 1?
Which would make the INNER JOIN fail. So you've either showed the wrong query, or the statement is incorrect. In either case, you can troubleshoot using this query:
SELECT dbo.Enquiries.EnquiryID,
dbo.QuoteLines.*
FROM dbo.DayBookEnquiries INNER JOIN
dbo.QuoteLines ON dbo.Enquiries.EnquiryID = dbo.QuoteLines.EnquiryID
It will show at least one record from QuoteLines.

SQL Server returns empty fields

I have a select script that runs 3 times a day in a 2005 SQL Server installation, a few times the return table has contained expected number of rows but without any values. The integer and date fields have zeros and the others are simply blank.
Since the problem occurs very rarely there is no way to supervise the database when the script runs and haven't been able to replicate the issue. My thought is that some other update in the database is causing the problem. Does anyone know about this problem?
Here is the script
SELECT DISTINCT
URL.Line,
RTrim(URL.DescriptionNote) AS [DescriptionNote],
SA1.Name AS [Name1],
SP1.Designation AS [Designation1],
SA2.Name [Name2],
SP2.Designation AS [Designation2],
RL.DistanceMeters,
dbo.RouteLinkTransportModeDesc(URL.TransportModeTypeNumber) AS TransportMode,
URL.THM,
URL.FirstWorkedDate,
URL.LastWorkedDate
FROM #RequiredRouteLink URL
INNER JOIN StopPoint AS SP1
ON SP1.JourneyPatternPointGid = URL.StartsAtPointGid
INNER JOIN StopArea AS SA1
ON SP1.IsPartOfStopAreaVersionId = SA1.VersionId
INNER JOIN StopPoint AS SP2
ON SP2.JourneyPatternPointGid = URL.EndsAtPointGid
INNER JOIN StopArea AS SA2
ON SP2.IsPartOfStopAreaVersionId = SA2.VersionId
LEFT JOIN verRouteLink AS RL
ON RL.StartsAtPointGid = URL.StartsAtPointGid
AND RL.EndsAtPointGid = URL.EndsAtPointGid
AND URL.TransportModeTypeNumber = RL.TransportModeTypeNumber
WHERE URL.StartsAtPointGid <> URL.EndsAtPointGid
AND (RL.EndsAtPointGid IS NULL OR RL.DistanceMeters = 0 OR RL.DistanceMeters IS NULL)
AND RL.[DeletedDateTime] IS NULL
ORDER BY FirstWorkedDate, THM, TransportMode, Line, DescriptionNote
I'm sure it is a data issue. The reason you are getting blank fields is most likely the LEFT JOIN.
You have 4 INNER JOINs, any one of which could cause you to have an empty result set. If one or more of those don't find a match, you have no results.
However, your LEFT JOIN means you will at least get the list of URL.Line, which is why you had the expected number of rows most likely.
Can you run a low level SQL trace - filtering it as much as possible to reduce the load of the trace [e.g., by application, etc.]