Case Statement within in Statement in MS SQL - sql

I want to compare two different tables in IN statement based on condition.
SELECT DISTINCT
cts.ContactType
,ISNULL(ctl.[Description], CONCAT('Unknown Contact Type: ',cts.ContactType)) AS [Description]
FROM
( SELECT Null AS [ContactType]
WHERE ISNULL(Null, '') <> ''
UNION ALL
SELECT DISTINCT cta.ContactType
FROM
(SELECT u.AccessUserID
FROM v2010_vUsers u
WHERE u.UserID = 'harry_1#cared_t'
UNION ALL
SELECT ur.AccessUserID
FROM v2010_UserRoles ur
WHERE ur.UserID = 'harry_1#cared_t') r --Roles user has
INNER JOIN v2010_UDV_ContactType_AccessMatrix_Full cta --ContactTypes Accessible
ON cta.AccessUserID = r.AccessUserID) cts --ContactTypes Selectable
LEFT JOIN v2010_ListEntries ctl --ContactType List
ON ctl.ListId='CONTACTTYPE' and ctl.Code = cts.ContactType
WHERE cts.ContactType In
(
CASE WHEN (SELECT dbo.f2010_IsFeatureAllowedInTenancy('ContactTypeSC', dbo.f2010_PartnerDivisionID('06b30841-2496-48ef-b91a-21f06a9299f2'))) = '1'
THEN (SELECT Code From v2010_ListEntries WHERE ListId='CONTACTTYPESC')
ELSE (SELECT Code From v2010_ListEntries WHERE ListId='CONTACTTYPE')
END
)
ERROR : Subquery returned more than 1 value. This is not permitted
when the subquery follows =, !=, <, <= , >, >= or when the subquery is
used as an expression.
Error is in following lines:
WHERE cts.ContactType In
(
CASE WHEN (SELECT dbo.f2010_IsFeatureAllowedInTenancy('ContactTypeSC', dbo.f2010_PartnerDivisionID('06b30841-2496-48ef-b91a-21f06a9299f2'))) = '1'
THEN (SELECT Code From v2010_ListEntries WHERE ListId='CONTACTTYPESC')
ELSE (SELECT Code From v2010_ListEntries WHERE ListId='CONTACTTYPE')
END
)
I am not able to use case when in IN statement. if I write WHERE cts.ContactType In (SELECT Code From v2010_ListEntries WHERE ListId='CONTACTTYPESC') it is working but I want to compare condition and based on condition compare table.

It is a bit hard to tell where the multiple rows problem is coming from, but I am thinking:
WHERE (dbo.f2010_IsFeatureAllowedInTenancy('ContactTypeSC', dbo.f2010_PartnerDivisionID('06b30841-2496-48ef-b91a-21f06a9299f2')) = '1' and
cts.ContactType In (SELECT Code From v2010_ListEntries WHERE ListId = 'CONTACTTYPESC')
) OR
(dbo.f2010_IsFeatureAllowedInTenancy('ContactTypeSC', dbo.f2010_PartnerDivisionID('06b30841-2496-48ef-b91a-21f06a9299f2')) <> '1' and
cts.ContactType In (SELECT Code From v2010_ListEntries WHERE ListId = 'CONTACTTYPE'')
)
Or, more simply as:
cts.ContactType In (SELECT le.Code
FROM v2010_ListEntries le CROSS JOIN
(VALUES (CASE WHEN dbo.f2010_IsFeatureAllowedInTenancy('ContactTypeSC', dbo.f2010_PartnerDivisionID('06b30841-2496-48ef-b91a-21f06a9299f2')) THEN 'CONTACTTYPESC' ELSE 'CONTACTTYPESC' END)) v(listId)
WHERE le.ListId = v.ListId
)

Related

How to solve this error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery?

I have a query that works on SQLAnywhere, but for some reason does not work on SSMS, tell me what is wrong with it, because I get an error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
SELECT (CASE
WHEN EXISTS (select 1 from READCHK_READSEQ_OVRCOMP where READCHK_ID = :readChkId AND READSEQ_ID = :readSeqId) THEN 'M'
WHEN ( COUNT(*) = Coalesce(SUM((SELECT COUNT(*) FROM READCHKFLEX flx WHERE flx.READCHKFLD_ID = rcfld.READCHKFLD_ID AND flx.READCHK_ID = :readChkId) ), 0 )) THEN 'A'
ELSE 'I' END) CompletionStatus
FROM READSEQFLD rsfld
JOIN READSEQ rseq on rseq.READSEQ_ID = rsfld.READSEQ_ID
JOIN READCHKPAGEFLD rcpf on rcpf.READCHKTYPE_ID = rseq.READCHKTYPE_ID and rcpf.READCHKFLD_ID = rsfld.READCHKFLD_ID
JOIN READCHKFLD rcfld on rcfld.READCHKFLD_ID = rcpf.READCHKFLD_ID
WHERE rsfld.READSEQ_ID = :readSeqId
AND Upper(rsfld.ACTIVATE_FLG) = 'Y'
AND rcfld.CALFORM_ID IS NULL
AND (rcpf.fld_properties is null or Upper(rcpf.fld_properties) <> 'HIDE');
How to fix that?
SQL Server doesn't allow aggregates on expressions containing sub queries.
I think the following should preserve your original behaviour
Append a CTE definition before the existing SELECT
WITH flx_agg
AS (SELECT COUNT(*) AS Cnt,
READCHKFLD_ID
FROM READCHKFLEX flx
WHERE flx.READCHK_ID = :readChkId
GROUP BY READCHKFLD_ID)
SELECT ...
Add an outer join to that to your existing join conditions
LEFT JOIN flx_agg
ON flx_agg.READCHKFLD_ID = rcfld.READCHKFLD_ID
Change the offending CASE WHEN condition to
WHEN COUNT(*) = COALESCE(SUM(flx_agg.Cnt), 0)

Case statement in multiple conditions?

I want to check the column mr.name, if mr.name is null then i have to replace mr.name as mr.ticket_no. How? Can use if else or case?
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
mr.name as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65
When i use like this
case when mr.name is null then '' else mr.ticket_no = grn.mr_no as mr_no
it will throw an error
if mr.name = null means i have to replace mr.name = mr.ticket_no. I want to check the column mr.name, if mr.name is null then i have to replace mr.name as mr.ticket_no
You can use coalesce() to replace null with anything:
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
coalesce(mr.name,mr.ticket_no) as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65
But if you are comfortable with case when then use as below:
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
(case when mr.name is null then mr.ticket_no else mr.name end) as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65

Cannot use an aggregate or a subquery

I'm trying to group this case expression but unfortunately I'm getting an error.
select da.order_id, osl.itemid, sum(case when osl.sku = '00005' then 0 when osl.sku = '00006' then 0 else osl.price * sil.quantity end) merchcost, sum(sil.merchUnitCost * sil.quantity) cogs, sum(sil.quantity) quantity,
CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then 1
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then 1
else 0
END as isAdmin,
CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then CAST('subscriptionskus' as varchar(MAX))
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then CAST('subscriptionprogram' as varchar(MAX))
else 'NotListed'
END as SubTable
from #dispatchAmounts da
inner join orderstates os on os.order_id = da.order_id
inner join orderstatelines osl on osl.orderState_id = os.orderState_id
inner join shippingIntentLines sil on sil.orderStateLine_id = osl.orderStateLine_id and da.shippingIntent_nbr = sil.shippingIntent_nbr
where da.code = 'merch' and sil.quantity > 0
group by da.order_id, osl.itemid, CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then 1
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then 1
else 0
END,CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then CAST('subscriptionskus' as varchar(MAX))
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then CAST('subscriptionprogram' as varchar(MAX))
else 'NotListed'
END
ERROR:
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
Is there anyway I can make this work?
I have a couple of suggestions. You are using select * in your case statements , but the columns referenced by '*' are not in your group by clause. To add them would be a bad way to fix the problem. Instead use ' select 1 ' and see what happens.
Second recommendation is to just not use the when exists rather use left join using sub queries and use those in your case statements.
So what I did is.
1. Removed the Case Statement on the Group By.
2. Modified the SubQueries on the Case Statement. Followed #Shiv Sidhu recommendation.
Thanks for everyone.

How to use a non-existing column in sql query

I am working in SQL server 2012. I have to write a sql statement where I first assign a value to [Pay_Type], which is a non-existing column (not sure whether it can be called as variable or not) and based upon its value I want to use it in another case statement as shown below
SELECT sp.First_Name, [Pay_Type] = CASE WHEN NOT EXISTS(SELECT '1' FROM
PERSON_SALARY ps WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL)
THEN 'Hourly' ELSE 'Salary' END,
HOURLY_RATE = CASE WHEN [Pay_Type] = 'Hourly' THEN pj.HOURLY_RATE ELSE
'0.00' END
FROM SEC_PERSON sp
LEFT OUTER JOIN PERSON_JOB pj ON sp.PERSON_ID = pj.PERSON_ID
WHERE sp.END_DATE IS NOT NULL
But I am getting "Invalid column name 'Pay_Type' " error.
Column aliases cannot be re-used in the same SELECT where they are define. The typical answer is to use a subquery or CTE. I also like using a lateral join:
SELECT sp.First_Name, s.Pay_Type,
HOURLY_RATE = (CASE WHEN s.Pay_Type = 'Hourly' THEN pj.HOURLY_RATE ELSE
'0.00' END)
FROM SEC_PERSON sp LEFT OUTER JOIN
PERSON_JOB pj
ON sp.PERSON_ID = pj.PERSON_ID OUTER APPLY
(SELECT (CASE WHEN NOT EXISTS (SELECT 1
FROM PERSON_SALARY ps
WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL
)
THEN 'Hourly' ELSE 'Salary'
END) as PayType
) s
WHERE sp.END_DATE IS NOT NULL

multiple errors in using with function in select statement

I'm having some problems with my select statement. When I try to execute it, it gives 3 errors
Must specify table to select from
An object or column name is missing or empty for SELECT INFO statements. verify each column
has a name. For other statements, look for empty alias names. Aliases defined...
Column name or number of supplied values does not match table definition.
WITH A AS
(SELECT ROW_NUMBER() OVER (ORDER BY
CASE
WHEN #pOrderBy = 'SortByName' THEN colPortAgentVendorNameVarchar
WHEN #pOrderBy = 'SortByCOuntry' THEN colCountryNameVarchar
WHEN #pOrderBy = 'SortByCity' THEN colCityNameVarchar
END,
colPortAgentVendorNameVarchar
) xRow, A.*
FROM
(
SELECT DISTINCT
V.colPortAgentVendorIDInt,
colPortAgentVendorNameVarchar = RTRIM(LTRIM(V.colPortAgentVendorNameVarchar)),
C.colCountryNameVarchar,
Y.colCityNameVarchar,
V.colContactNoVarchar,
V.colFaxNoVarchar,
V.colEmailToVarchar,
V.colWebsiteVarchar,
BR.colBrandIdInt,
PR.colPriorityTinyint,
colBrandCodeVarchar = RTRIM(LTRIM(BR.colBrandCodeVarchar))
FROM dbo.TblVendorPortAgent V
LEFT JOIN TblCountry C ON C.colCountryIDInt = V.colCountryIDInt
LEFT JOIN TblCity Y ON Y.colCityIDInt = V.colCityIDInt
LEFT JOIN tblBrandAirportPortAgent PR ON PR.colPortAgentVendorIDInt = V.colPortAgentVendorIDInt
AND PR.colIsActiveBit = 1
LEFT JOIN TblBrand BR ON BR.colBrandIdInt = PR.colBrandIdInt
AND BR.colIsActiveBit = 1
WHERE V.colIsActiveBit = 1
AND V.colPortAgentVendorNameVarchar LIKE '%'+ #pPortAgentVendor +'%'
AND (PR.colBrandIdInt = #pBrandID OR #pBrandID = 0)
) A
)
INSERT INTO #tempPortAgent
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END FROM A LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
;WITH QQ AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY Q.colPortAgentVendorIDInt ORDER BY xRow,
ContractStatusOrder,
colDateCreatedDate DESC
)ContractRow,*
FROM
(
SELECT DISTINCT GG.*, B.colContractIdInt, B.colContractStatusVarchar, B.colDateCreatedDate ,
ContractStatusOrder = CASE WHEN B.colContractStatusVarchar = 'Approved' THEN 1 ELSE '2' END
FROM #tempPortAgent GG LEFT JOIN TblContractPortAgent B ON GG.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
) Q
)SELECT * INTO #tempPortAgentWithContract
SELECT * FROM #tempPortAgentWithContract
I don't really know where its showing, because the errors are saying that these are inside the select statements inside.
1- Use Select Into instead of Insert into select
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END
Into #tempPortAgent
FROM A
LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
2- SELECT * INTO #tempPortAgentWithContract is incorrect syntax. you must use following format:
SELECT * INTO #tempPortAgentWithContract From QQ