Nested case statements in inner joins - sql

Having issues with that I think can be solved by a case statement, but it keeps rejecting my sql. Basically, I'm introducing a new parameter to existing SQL and need to react different ways depending on what it is... sounded like a case statement to me, but it keeps rejecting it. Any thoughts?
Original
INNER JOIN T_CASE CF ON
(
A.AWESOME_ID = CF.AWESOME_ID
// Several more awesome conditions
)
AND
(
(
cy.SOMEFLAG = 0
AND CF.SOMEDATE IS NOT NULL
)
OR
(
cy.SOMEFLAG = 1
AND CF.CASE_TYPE = 1
AND CF.SOMEDATE IS NOT NULL
)
)
Attempt #1
INNER JOIN T_CASE CF ON
(
A.AWESOME_ID = CF.AWESOME_ID
// Several more conditions
)
AND
(
// Just this part is what the new parameter applies to
CASE WHEN #NEWPARAM = 1 THEN
(
(
cy.SOMEFLAG = 0
AND CF.SOMEDATE IS NOT NULL
)
OR
(
cy.SOMEFLAG = 1
AND CF.CASE_TYPE = 1
AND CF.SOMEDATE IS NOT NULL
)
)
ELSE
(
(
cy.SOMEFLAG = 0
AND CF.SOMEDATE IS NULL
)
OR
(
cy.SOMEFLAG = 1
AND CF.CASE_TYPE = 0
OR CF.SOMEDATE IS NULL
)
)
END
)

In general, I think it is a better idea to use basic logical constructs in condition clauses, rather than the case. You can readily do this:
INNER JOIN T_CASE CF ON
(
A.AWESOME_ID = CF.AWESOME_ID
// Several more conditions
)
AND
(
(
#NEWPARAM = 1 AND
cy.SOMEFLAG = 0 AND
CF.SOMEDATE IS NOT NULL
)
OR
(
#NEWPARAM = 1 AND
cy.SOMEFLAG = 1 AND
CF.CASE_TYPE = 1 AND
CF.SOMEDATE IS NOT NULL
)
OR
(
#NEWPARAM <> 1 AND
cy.SOMEFLAG = 0 AND
CF.SOMEDATE IS NULL
)
OR
(
#NEWPARAM <> 1 AND
((cy.SOMEFLAG = 1 AND CF.CASE_TYPE = 0) OR
CF.SOMEDATE IS NULL
)
)
)

You can't use the case statement to dynamically include/exclude portions of the SQL statement, but you can still get a similar effect like this
INNER JOIN T_CASE CF ON
(
A.AWESOME_ID = CF.AWESOME_ID
// Several more conditions
)
AND
(
// Just this part is what the new parameter applies to
1 = CASE WHEN
#NEWPARAM = 1
and
(
cy.SOMEFLAG = 0
AND CF.SOMEDATE IS NOT NULL
)
OR
(
cy.SOMEFLAG = 1
AND CF.CASE_TYPE = 1
AND CF.SOMEDATE IS NOT NULL
)
THEN 1
CASE WHEN
#NEWPARAM <> 1
and
(
(
cy.SOMEFLAG = 0
AND CF.SOMEDATE IS NULL
)
OR
(
cy.SOMEFLAG = 1
AND CF.CASE_TYPE = 0
OR CF.SOMEDATE IS NULL
)
)
THEN 1
ELSE 0
END
)
Basically we're returning 1 for rows that meet the criteria, and 0 for rows that don't and comparing that against the value 1.

Related

ORA-00905: missing keyword in where case statement

select m_seqe
,m_emai
,m_phon
,e_seqe
,m_id
,
( case
when (:M_STAT = 0 ) and (m_id is not null ) then 'a'
when (:M_STAT = 0 ) and (m_id is null ) then 'b'
when (:M_STAT = 200 ) then 'c'
Else ' - ' end ) as Stat
from m_users
where m_stat = :M_STAT
and m_id =
case when (:M_ID = 0 ) then m_id is null
when (:M_ID ='a') then m_id is not null
else 'do nothing' end
The way you put it & I understood what you're saying, that would be a combination of several OR conditions:
WHERE m_stat = :M_STAT
AND ( ( m_id IS NULL AND :m_id = 0)
OR ( m_id IS NOT NULL AND :m_id = 'a')
OR ( m_id = 'do nothing'
);
You can't use a case expression to determine the logic in a filter; so this doesn't make sense and is what the parser is complaining about:
and m_id =
case when (:M_ID = 0 ) then m_id is null
when (:M_ID ='a') then m_id is not null
else 'do nothing' end
You could potentially have a case expression that evaluates to a value which you then compare against your column value, ut it doesn't seem to make sense here either, not least because null handling is a little awkward.
You seem to want to replace that with simple Boolean logic:
where m_stat = :M_STAT
and ((:M_ID = 0 and m_id is null)
or (:M_ID ='a' and m_id is not null))
or to be consistent in treating the bind variable as a string:
where m_stat = :M_STAT
and ((:M_ID = '0' and m_id is null)
or (:M_ID ='a' and m_id is not null))
There is no 'else' to worry about; your 'do nothing' string seems to be a placeholder that isn't intended to actually match against anything I.e. it's not a real m_id value you look for). If neither combined condition is true for a given row then the overall condition is false, and there won't be a match for that row and it will be filtered out.
Your problem is ambiguous but can be implemented as follows
select m_seqe
,m_emai
,m_phon
,e_seqe
,m_id
,
( case
when (:M_STAT = 0 ) and (m_id is not null ) then 'a'
when (:M_STAT = 0 ) and (m_id is null ) then 'b'
when (:M_STAT = 200 ) then 'c'
Else ' - ' end ) as Stat
from m_users
where m_stat = :M_STAT and
(
case when when (m_id IS NOT NULL AND :m_id = 'a') then 'a'
when (m_id IS NULL AND :M_ID = 0 ) then 'b'
when (m_id = 'do nothing') then 'c'
when 'd' end
) in ('a','b','c')

optimize complex stored procedure

I have a very complex stored procedure and i am not that strong in SQL, please any one who has a strong SQL expertise and can help me optimize or at least can give me a hint, the procedure selects the inbox messages from database for specific user and it contains many other parameters such as paging and categories and also language input and many other details:
ALTER PROCEDURE [dbo].[Inbox]
#ConfidentialityIds NVARCHAR(100) = '0,1,2,3',
#UrgencyIds NVARCHAR(100) = '0,1,2,3',
#CorrespondenceCategoryIds NVARCHAR(100) = '1,2,3,5,6,7',
#CorrespondenceExtendedCategoryIds NVARCHAR(MAX),
#IsPrivate bit = 0,
#IsSaved bit = 0,
#Importantance VARCHAR(10) = '0, 1',
#UserId uniqueidentifier,
#SelectedPage int = 1,
#PageSize int = 25,
#Now bigint,
#IsImpersonated bit,
#ActualLoggedInUserId uniqueidentifier,
#IsEnglish bit,
#OnlyArchived bit = null,
#replaceNameWithEntName bit,
#entityIds nvarchar(MAX),
#OnlyLate bit = 0,
#Statuses NVARCHAR(100) ='1,2,3,4,5',
#ApplyPageFilter bit = 1,
#IsBundled int,
#showArchivedInCCInbox bit = 0,
#appModuleId INT = 0
WITH RECOMPILE
As
BEGIN
SET transaction isolation level read uncommitted
DECLARE #lFirstRec INT, #lLastRec INT, #lTotalRows INT
SET #lFirstRec = ( #SelectedPage - 1 ) * #PageSize
SET #lLastRec = ( #SelectedPage * #PageSize + 1 )
SET #lTotalRows = #lFirstRec - #lLastRec + 1
DECLARE #isPersonalDelegationAvailable BIT = 0
IF EXISTS(
SELECT 1
FROM DelegatedToEntityUsers d
WHERE d.DelegatedToUserId = #ActualLoggedInUserId
AND d.DelegatedFromUserId = #UserId
AND
(
d.DelegatedToEntityId IS NULL OR d.DelegationType = 1
))
BEGIN
SET #isPersonalDelegationAvailable = 1
END
DECLARE #tblEntities TABLE(Value INT)
INSERT INTO #tblEntities
SELECT Value FROM SplitCommaUniqueValues(#entityIds)
Select * from (
Select (ROW_NUMBER() OVER (ORDER BY K.ActionDate DESC, K.CorrespondenceDate DESC)) AS RowIndex,
Count(*) over () AS TotalCount,*
from (
select (ROW_NUMBER() OVER (PARTITION BY CorrespondenceID Order by CorrespondenceID DESC)) AS CorrId, *
from (
SELECT Distinct * FROM
(
SELECT
CONVERT(VARCHAR(100), R.CorrespondenceActionRecipientID) Id,
A.CorrespondenceActionID ActionId,
(CASE WHEN R.RecipientType IS NULL THEN NULL ELSE CAST(RecipientType AS INT) END) RecipientType,
A.ActionTypeId,
(CASE when #IsEnglish = 1 then ATypes.FriendlyTextEN else ATypes.FriendlyTextAR end) ActionTypeName,
A.ActionCreatedByUserID SentById,
CASE
when #replaceNameWithEntName = 0 then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentByEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentByEntity.EntityNameEn else SentByEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentByEntity.EntityID in (SELECT Value FROM #tblEntities) then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
END SentByFrom,
A.WithDelegateFromUserID OnBehalfOfId,
ISNULL(WithDelegateFromUser.ShortName, WithDelegateFromUser.EmployeeName) OnBehalfOfName,
R.UserId SentToId,
CASE
when #replaceNameWithEntName = 0 then ISNULL(SentToUser.ShortName, SentToUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentToEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentToEntity.EntityID in (SELECT Value FROM #tblEntities) then isnull(ISNULL(SentToUser.ShortName, SentToUser.EmployeeName), case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end)
END SentToName,
R.EntityID SentToEntityId,
SentToEntity.EntityNameAR SentToEntityNameAR,
SentToEntity.EntityNameEN SentToEntityNameEN,
R.Seen,
(CASE WHEN MR.CorrespondenceActionRecipientID IS NOT NULL THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsReadByUser,
CAST(ISNULL(FollowedByUser.IsFollowedByUser, 0) AS BIT) IsFollowedByUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND UserId = #UserId AND AssignedByUserId IS NOT NULL) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowToUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND AssignedByUserId = #UserId) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowByUser,
A.CorrespondenceID,
A.ActionDate,
A.ActionDeadlineDate,
C.CompletionDate,
C.CorrespondenceDeadlineDate CorrDeadlineDate,
C.OwnerUserID CorrOwnerId,
C.ChildNo ChildNo,
OwnerUser.EmployeeName CorrOwnerName,
C.Important,
C.UrgencyId,
C.LetterCorrespondenceId,
(CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) UrgencyText,
C.ConfidentialityId,
(CASE when #IsEnglish = 1 then Confid.TextEN else Confid.TextAR end) ConfidentialityText,
C.CorrespondenceCategoryId CategoryId,
C.CorrespondenceClassificationID CorrespondenceClassificationID,
(CASE when #IsEnglish = 1 then CCat.TextEN else CCat.TextAR end) CategoryName,
CCat.ColorClass ColorClass,
C.Subject,
c.CorrespondenceFormula,
C.InternalSenderEntityId,
C.InternalRecipientEntityId,
C.[Sequence] [Sequence],
C.Year,
C.CompletionStatus Status,
Null Number,
(CASE WHEN (
(
(A.ActionDeadlineDate IS NOT NULL AND A.ActionDeadlineDate < #Now)
OR
(C.CorrespondenceDeadlineDate IS NOT NULL AND C.CorrespondenceDeadlineDate < #Now)
)
AND
C.[Closed-Archived] = 0) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsLate,
CAST(0 AS BIT) HasAnyEvents,
C.CreatedByUserId,
CreatedByUser.EmployeeName CreatedByUserName,
CAST(C.CorrespondenceDate AS VARCHAR(50)) CorrDate,
C.CorrespondenceDate,
C.[Closed-Archived] ClosedArchived,
C.IsSaved SavedActionTaken,
((CASE WHEN C.Important = 1 THEN CASE WHEN #IsEnglish = 1 THEN N'Important' ELSE N'هامة' END ELSE '' END) + (CASE WHEN C.Important = 1 AND C.UrgencyID <> 0 THEN CASE WHEN #IsEnglish = 1 THEN N' and ' ELSE N' و ' END ELSE '' END) + (CASE WHEN C.UrgencyID <> 0 THEN (CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) ELSE '' END)) ImportantUrgencyText,
CAST(C.IsAutoSaved AS BIT) IsAutoSaved,
-- *******************************************************************
rem.ReminderDate as CorrespondenceReminderDateTime,
remAction.ReminderDate as ActionReminderDateTime
FROM (
SELECT * FROM Correspondences CC
WHERE CC.IsDeleted = 0
AND CC.LetterCorrespondenceId IS NULL
AND (CC.ConfidentialityId IN (SELECT [Value] FROM SplitCommaUniqueValues(#ConfidentialityIds)))
AND
( #IsPrivate = 0 OR
(
#IsPrivate = 1 AND CC.IsForPresident = 1
)
)
AND
(
(CC.IsSaved = case when #IsSaved =1 then 1 else CC.IsSaved end)
)
AND (#appModuleId = 0 OR CC.AppModuleId = #appModuleId)
AND (CC.UrgencyID IN (SELECT value FROM SplitCommaUniqueValues(#UrgencyIds)))
AND (CC.Important IN (SELECT value FROM SplitCommaUniqueValues(#Importantance)))
AND CC.CompletionStatus IN(SELECT value FROM SplitComma(#Statuses))
) C
LEFT JOIN CorrespondenceExtendedDetails CorrExt
ON CorrExt.CorrespondenceID = C.CorrespondenceID
LEFT JOIN CorrespondenceActions A
ON C.CorrespondenceID = A.CorrespondenceID
AND A.IsDeleted = 0
AND A.ActionTypeID != 7 -- إنهاء التذكير
LEFT JOIN CorrespondenceActionRecipients R
ON A.CorrespondenceActionID = R.CorrespondenceActionID
AND (
R.AsCopy = 1
)
JOIN Urgencies U
ON C.UrgencyID = U.ID
JOIN ActionTypes ATypes
ON A.ActionTypeID = ATypes.ID
JOIN CorrespondenceCategories CCat
ON C.CorrespondenceCategoryId = CCat.ID
JOIN Confidentialities Confid
ON C.ConfidentialityID = Confid.ID
LEFT JOIN Users ActionCreatedByUser
ON A.ActionCreatedByUserID = ActionCreatedByUser.UserId
LEFT JOIN Users WithDelegateFromUser
ON A.WithDelegateFromUserID = WithDelegateFromUser.UserID
LEFT JOIN Entities SentByEntity
ON A.ActionCreatedByUserEntityId = SentByEntity.EntityID
LEFT JOIN Users SentToUser
ON R.UserId = SentToUser.UserId
LEFT JOIN Entities SentToEntity
ON R.EntityID = SentToEntity.EntityID
LEFT JOIN Users OwnerUser
ON C.OwnerUserID = OwnerUser.UserId
LEFT JOIN Users CreatedByUser
ON C.CreatedByUserID = CreatedByUser.UserId
LEFT JOIN MarkAsReads MR
ON R.CorrespondenceActionRecipientID = MR.CorrespondenceActionRecipientID
AND MR.UserId = #UserId
OUTER APPLY
(
SELECT TOP 1 1 IsFollowedByUser
FROM CorrespondenceFollowups CF
WHERE CF.CorrespondenceId = C.CorrespondenceID
AND CF.UserId = #UserId
AND CF.AssignedByUserId IS NULL
) FollowedByUser
-- *******************************************************************
LEFT JOIN LinkedCorrespondenceSchedules CS on CS.CorrespondenceID = C.CorrespondenceID
LEFT JOIN Reminder rem on rem.ReferenceId=C.CorrespondenceID AND rem.ReferenceType = 1 AND rem.CreatedByUserId=#UserId AND (rem.[Status] = 1 OR rem.[Status] = 2)
Left JOIN Reminder remAction on remAction.ReferenceId = A.CorrespondenceActionID AND remAction.ReferenceType = 2 AND remAction.CreatedByUserId=#UserId AND (remAction.[Status] = 1 OR remAction.[Status] = 2)
-- *******************************************************************
WHERE (
(C.CorrespondenceCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceCategoryIds)) AND CorrExt.CorrespondenceExtendedCategoryId IS NULL)
OR (CorrExt.CorrespondenceExtendedCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceExtendedCategoryIds)))
)
AND
(
-- Personal
(
(
(#IsImpersonated = 0 AND R.UserId = #UserId)
OR
(#IsImpersonated = 1 AND R.UserId = #UserId AND #isPersonalDelegationAvailable = 1)
)
AND R.RecipientType = 1 AND R.UserId Is Not null
)
OR
-- Me as Manager (Impersonation mode handled from code by sending the proper Entity Ids.
(
(R.EntityID IN (SELECT Value FROM #tblEntities) AND R.EntityID Is Not null AND R.RecipientType != 1)
)
)
AND C.[Closed-Archived] = Case When #showArchivedInCCInbox = 1 Then 0 Else C.[Closed-Archived] End
AND R.UserTokeAction = 0
AND NOT EXISTS (
SELECT 1 FROM Correspondences CC
INNER JOIN CorrespondenceLinks CL
ON CC.CorrespondenceID = CL.LinkedCorrespondenceID AND CC.CorrespondenceID = C.CorrespondenceID AND CL.LinkTypeID = #IsBundled
)
) T
WHERE T.LetterCorrespondenceId is null
) as ttt
) K where CorrId = 1
)N where (#ApplyPageFilter = 0 OR ( RowIndex > #lFirstRec AND RowIndex < #lLastRec))
Order by
ActionDate DESC, CorrespondenceDate
option(recompile)
END

Postgres Error: More than one row returned by a subquery used as an expression. 21000

I'm trying to insert distinct rows into a table however, I'm receiving the error in the title. What I don't understand is that I have set the LIMIT to 1 as I assumed this would solve the issue.
Can anyone please shed some light on this?
ERROR: more than one row returned by a subquery used as an expression.
INSERT INTO reports.sem_attribution_v2
SELECT DISTINCT
tsa.user_id,
tsa.transfer_date,
tsa.engine,
tsa.campaign_id,
tsa.adgroup_id,
(CASE
WHEN tsa.engine = 'quora' THEN NULL
WHEN tsa.source ILIKE '%uac%' THEN (
SELECT
account
FROM reports.lookup_uac_elements
WHERE campaign_id = tsa.campaign_id
LIMIT 1)
WHEN tsa.engine = 'google' THEN (
SELECT
pse.account_name
FROM reports.lookup_paid_search_elements pse
WHERE pse.campaign_id = tsa.campaign_id
AND pse.adgroup_id = tsa.adgroup_id
LIMIT 1)
WHEN tsa.engine = 'bing' THEN (
SELECT
lbe.account_name
FROM reports.lookup_bing_elements lbe
WHERE lbe.campaign_id = tsa.campaign_id
AND lbe.adgroup_id = tsa.adgroup_id
LIMIT 1
)
ELSE NULL
END) as account_name,
(
CASE
WHEN tsa.engine = 'quora' THEN NULL
WHEN tsa.source ILIKE '%uac%' THEN (
SELECT
lue.campaign
FROM reports.lookup_uac_elements lue
WHERE lue.campaign_id = tsa.campaign_id
)
WHEN tsa.engine = 'google' THEN (
SELECT
pse.campaign_name
FROM reports.lookup_paid_search_elements pse
WHERE pse.campaign_id = tsa.campaign_id
AND pse.adgroup_id = tsa.adgroup_id
LIMIT 1
)
WHEN tsa.engine = 'bing' THEN (
SELECT
lbe.campaign_name
FROM reports.lookup_bing_elements lbe
WHERE lbe.campaign_id = tsa.campaign_id
AND lbe.adgroup_id = tsa.adgroup_id
LIMIT 1
)
ELSE NULL
END
) as campaign_name,
(CASE
WHEN tsa.engine = 'quora' THEN NULL
WHEN tsa.source ILIKE '%uac%' THEN NULL
WHEN tsa.engine = 'google' THEN (
SELECT
pse.adgroup_name
FROM reports.lookup_paid_search_elements pse
WHERE pse.campaign_id = tsa.campaign_id
AND pse.adgroup_id = tsa.adgroup_id
LIMIT 1
)
WHEN tsa.engine = 'bing' THEN (
SELECT
lbe.adgroup_name
FROM reports.lookup_bing_elements lbe
WHERE lbe.campaign_id = tsa.campaign_id
AND lbe.adgroup_id = tsa.adgroup_id
LIMIT 1
)
ELSE NULL
END) as adgroup_name,
tsa.creation_platform,
tsa.profile_country,
tsa.ltr_12m,
tsa.costs_12m,
tsa.ltv_12m,
tsa.first_paid_touch,
tsa.even_weights,
tsa.first_team_touch,
(CASE
WHEN tsa.profile_type = 'business' THEN 1
ELSE 0
END) as business,
tsa.content,
tsa.ltr_12m_r,
tsa.costs_12m_r,
tsa.ltv_12m_r,
(CASE
WHEN tsa.profile_type = 'consumer' THEN 1
ELSE 0
END) as consumer
FROM tmp_sem_attribution tsa;

Weird Divide by Zero Error in SQL

I have this query :
-- There are a select and joins in the query
--Then I have this Where part
WHERE
(
dbo.Table.Furnished IS NULL
OR dbo.Table.Furnished = 0
)
AND (
dbo.Table.Type2 = N'House'
)
AND (
dbo.Table.Type3 = N'ForSale'
)
AND (
dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250
)
AND (
dbo.Table.FixedArea> 25
)
AND (
CASE
WHEN dbo.Table.Segment1 = 1 THEN
'FirstGroup'
WHEN dbo.Table.Segment1 = 2 THEN
'SecondGroup'
WHEN dbo.Table.Segment1 = 3 THEN
'ThirdGroup'
ELSE
'Undefined'
END <> 'Undefined'
)
AND (
dbo.Table.Segment2 <> N'Undefined'
)
OR
(
dbo.Table.Furnished IS NULL
OR dbo.Table.Furnished = 0
)
AND (
dbo.Table.Type2 = N'Commercial'
)
AND (
dbo.Table.Type3 = N'ForSale'
)
AND (
dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250
)
AND (
dbo.Table.FixedArea> 25
)
AND (
CASE
WHEN dbo.Table.Segment1 = 1 THEN
'FirstGroup'
WHEN dbo.Table.Segment1 = 2 THEN
'SecondGroup'
WHEN dbo.Table.Segment1 = 3 THEN
'ThirdGroup'
ELSE
'Undefined'
END <> 'Undefined'
)
AND (
dbo.Table.Segment2 <> N'Undefined'
)
When I add this part below at the bottom of my original query (which doesn't have any division or something like that), I get Divide by zero error encountered.
OR
(
dbo.Table.Geo IS NOT NULL
)
AND (
dbo.Table.FixedArea > 0
)
AND (
dbo.Table.Price > 0
)
AND (
dbo.Table.RoomNumber LIKE N'%+%'
)
AND (
dbo.Table.Furnished IS NULL
OR dbo.Table.Furnished = 0
)
AND(
dbo.Table.Type3 = N'ForRent'
)
Why am I getting this divide by zero error? I'm not adding any division. I'm just adding some new filters. Please help me with this error. Thanks.
You actually do here dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250...and probably ToiletNumber is zero
EDIT: Try re-running your query by changing the above code to
dbo.Table.FixedArea / NULLIF(dbo.Table.ToiletNumber, 0) < 250
You div/0 is here:
(
dbo.Table.FixedArea/ dbo.Table.ToiletNumber < 250
)
This:
AND (
dbo.Table.FixedArea> 25
)
Probably removed any div/0
Now this:
AND (
dbo.Table.FixedArea > 0
)
Means that rows with a FixedArea between 0 and 25 probably has a 0 for ToiletNumber, and has to be evaluated
To fix:
case when ToiletNumber = 0 then 1
else dbo.Table.FixedArea/ dbo.Table.ToiletNumber
end <250

Cannot perform an aggregate function on an expression containing an aggregate or a subquery when taking SUM of a Column returned by CASE Statement

I am having a problem with the following SQL query. While executing, it gives error:
Msg 130, Level 15, State 1, Line 2
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
SELECT
sum(case when DESP_SCANNING.PALLET_NO != null then (select PALLETNO_MASTER.PALLET_WEIGHT from PALLETNO_MASTER where DESP_SCANNING.PALLET_NO= PALLETNO_MASTER.PALLET_NO and DESP_SCANNING.REGION_ID = PALLETNO_MASTER.REGION_ID) else (select CARTONNO_MASTER.CARTON_WEIGHT from CARTONNO_MASTER where DESP_SCANNING.CARTON_NO = CARTONNO_MASTER.CARTON_NO and DESP_SCANNING.REGION_ID = CARTONNO_MASTER.REGION_ID) end) as totweight
FROM CUSTOMER_MASTER, DESP_SCANNING, CARRIER_MASTER, DC_MASTER
WHERE CARRIER_MASTER.CARRIER_CODE = DESP_SCANNING.CARRIER_CODE AND
((DESP_SCANNING.PALLET_NO != null and DESP_SCANNING.PALLET_NO = (select PALLETNO_MASTER.PALLET_NO from PALLETNO_MASTER where DESP_SCANNING.REGION_ID = PALLETNO_MASTER.REGION_ID)) or(DESP_SCANNING.PALLET_NO = null and DESP_SCANNING.CARTON_NO = (select CARTONNO_MASTER.CARTON_NO from CARTONNO_MASTER where DESP_SCANNING.REGION_ID = CARTONNO_MASTER.REGION_ID))) AND
DESP_SCANNING.STATUS = 2
group by DESP_SCANNING.DC_NO, DESP_SCANNING.POD_DATE, CUSTOMER_MASTER.CUS_NAME, CARRIER_MASTER.CARRIER_NAME, DESP_SCANNING.AWB_NO,DC_MASTER.DESP_END_DATE_TIME, DESP_SCANNING.SCAN_DATE, DC_MASTER.PSR_LOAD_DATE_TIME
order by CARRIER_MASTER.CARRIER_NAME, DESP_SCANNING.POD_DATE
Error shows in this line:
sum(case when DESP_SCANNING.PALLET_NO != null then (select PALLETNO_MASTER. PALLET_WEIGHT from PALLETNO_MASTER where DESP_SCANNING.PALLET_NO= PALLETNO_MASTER.PALLET_NO and DESP_SCANNING.REGION_ID = PALLETNO_MASTER.REGION_ID) else (select CARTONNO_MASTER.CARTON_WEIGHT from CARTONNO_MASTER where DESP_SCANNING.CARTON_NO = CARTONNO_MASTER.CARTON_NO and DESP_SCANNING.REGION_ID = CARTONNO_MASTER.REGION_ID) end) as totweight,
So, what I can give instead of this.
It looks like you need to factor out the CASE ... construct (which has the subquery's that cause the error message) into the WHERE clause.
That is, first construct a single table that contains PALLET_WEIGHT or CARTON_WEIGHT as appropriate, in a single column, and do the SUM over that column. Genre SELECT SUM(x) FROM (your big complicated SELECT here).
(I'm not guaranteeing that this will be possible. It's just what I would try to do having read what the error message tells me. Bigger product experts than me could possibly tell you my idea won't work either.)
maybe this code will help you:
select sum(x.totweight) as totweight
from (
select
CARRIER_MASTER.CARRIER_NAME,
DESP_SCANNING.POD_DATE,
case when DESP_SCANNING.PALLET_NO != null then(
select PALLETNO_MASTER.PALLET_WEIGHT
from PALLETNO_MASTER
where DESP_SCANNING.PALLET_NO = PALLETNO_MASTER.PALLET_NO
and DESP_SCANNING.REGION_ID = PALLETNO_MASTER.REGION_ID
)
else(
select CARTONNO_MASTER.CARTON_WEIGHT
from CARTONNO_MASTER
where DESP_SCANNING.CARTON_NO = CARTONNO_MASTER.CARTON_NO
and DESP_SCANNING.REGION_ID = CARTONNO_MASTER.REGION_ID
)
end as totweight
from CUSTOMER_MASTER,
DESP_SCANNING,
CARRIER_MASTER,
DC_MASTER
where CARRIER_MASTER.CARRIER_CODE = DESP_SCANNING.CARRIER_CODE
and (
(
DESP_SCANNING.PALLET_NO != null
and DESP_SCANNING.PALLET_NO = (
select PALLETNO_MASTER.PALLET_NO
from PALLETNO_MASTER
where DESP_SCANNING.REGION_ID = PALLETNO_MASTER.REGION_ID
)
)
or (
DESP_SCANNING.PALLET_NO = null
and DESP_SCANNING.CARTON_NO = (
select CARTONNO_MASTER.CARTON_NO
from CARTONNO_MASTER
where DESP_SCANNING.REGION_ID = CARTONNO_MASTER.REGION_ID
)
)
)
and DESP_SCANNING.status = 2
group by DESP_SCANNING.DC_NO,
DESP_SCANNING.POD_DATE,
CUSTOMER_MASTER.CUS_NAME,
CARRIER_MASTER.CARRIER_NAME,
DESP_SCANNING.AWB_NO,
DC_MASTER.DESP_END_DATE_TIME,
DESP_SCANNING.SCAN_DATE,
DC_MASTER.PSR_LOAD_DATE_TIME
) x
order by x.CARRIER_NAME, x.POD_DATE