When ever I am using the below query :
SELECT
AC.iJobID as JobID,
ROW_NUMBER()OVER (ORDER BY AC.iJobID) AS RowNumber,
(SELECT COUNT (*) FROM tbUS_ReferJob WHERE iJobId_FK = 202424 AND sReferredFrom = 'F' AND iUserId_FK = 9550) AS FaceBook_Applications
FROM tbUS_AffiliateJobCount AC,tbUS_ReferJob RJ
WHERE AC.iJobID = 202424 AND RJ.iJobId_FK = 202424
GROUP BY AC.iJobID
It is giving the correct result.
JobID RowNumber FaceBook_Applications
202424 1 2
But when I use the query below
SELECT
AC.iJobID as JobID,
ROW_NUMBER()OVER (ORDER BY AC.iJobID) AS RowNumber,
SUM(CASE WHEN RJ.sReferredFrom = 'F' THEN 1 ELSE 0 END) AS FaceBook_Applications
FROM tbUS_AffiliateJobCount AC,tbUS_ReferJob RJ
WHERE AC.iJobID = 202424 AND RJ.iJobId_FK = 202424
GROUP BY AC.iJobID
It is giving the incorrect result
JobID RowNumber FaceBook_Applications
202424 1 12
Now my questions are
- What is the reason behind it?
- How can I make it using
SUM()function to lower the cost?
Any suggestion will be helpful.
Thanks for your time.
UPDATE
SELECT AC.iJobID as JobID,
ROW_NUMBER()OVER (ORDER BY AC.iJobID) AS RowNumber,
SUM(CASE WHEN (RJ.sReferredFrom = 'F' AND RJ.iJobId_FK = 202424 AND RJ.iUserId_FK = 9550) THEN 1 ELSE 0 END) AS FaceBook_Applications
FROM tbUS_AffiliateJobCount AC,tbUS_ReferJob RJ
WHERE AC.iJobID = 202424 AND RJ.iJobId_FK = 202424
GROUP BY AC.iJobID
It is giving :
JobID RowNumber FaceBook_Applications
202424 1 8
UPDATE 2
SELECT iJobID_FK, sReferredFrom FROM tbUS_ReferJob WHERE iUserID_FK=9550 AND iJobID_FK=202424 AND sReferredFrom='F'
Result:
iJobID_FK sReferredFrom
202424 F
202424 F