Case within Case when combining multiple columns into one - sql

I'm trying to create a query that will take multiple columns in a View and bring it into one column in the query. The values from each column needs to be separated by '|' (pipe).
I've tried:
1) (expression1 + '|' + expression2) AS xxxx, but if one expression has a null value, it makes the results 'null'.
2) CAST (expression1 as varchar (10)) + '|' + CAST (expression2 as varchar (10)) AS xxxx, but get the same results.
3) CASE (expression1 is null) then (' ') else (expression1) +'|' + CASE (expression2 is null) then (' ') else (expression2) END AS xxxx, but I get a syntax error near the keyword 'AS'.
Here's the full query using CASE.
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, CASE WHEN dbo.View_MYAccess_Period1.CRSGRP1 is null then ' ' else dbo.View_MYAccess_Period1.CRSGRP1 + ' |' +
CASE WHEN dbo.View_MYAccess_Period2.CRSGRP2 is null then ' ' else dbo.View_MYAccess_Period2.CRSGRP2
END AS CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID
Any help for this newbie would be greatly appreciated!

Use ISNULL function,
SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, ISNULL(dbo.View_MYAccess_Period1.CRSGRP1,' ') + ' |' +
ISNULL(dbo.View_MYAccess_Period2.CRSGRP2,' ') CRSGRP
FROM dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID

In example 1, you might use the COALESCE(expression, fallback) function to force expression to return a fallback value if the expression is null. (Then tweak the rest of the logic accordingly.)
In your example 3, you need another END keyword:
CASE
(expression1 is null) then (' ')
ELSE (expression1) +'|' +
CASE (expression2 is null) then (' ') else (expression2) END
END AS xxxx

Related

some weird signs appearing on SQL SERVER Query output

i have written a SELECT Query on SQL SERVER 2014 . I have got the desired output . but an apostrophe symbol(') appearing on 'TaskAction' field data(at the end of each data). here it is my script:
SELECT
WOtask.PK,
WOPK,
TaskNo,
TaskAction =
CASE
WHEN WOTask.AssetPK IS NOT NULL THEN '<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL AND
Asset.Vicinity <> '''' THEN RTRIM(Asset.Vicinity) + ': '
ELSE ''''
END + WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
ELSE WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
END,
Rate,
Measurement,
Initials,
Fail,
Complete,
Header,
LineStyle,
WOtask.Comments,
WOtask.NotApplicable,
WOTask.Photo1,
WOTask.Photo2
FROM WOtask WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WOTask.AssetPK
LEFT OUTER JOIN AssetSpecification
ON AssetSpecification.PK = WOTask.AssetSpecificationPK
WHERE (WOPK IN (SELECT
WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK)
ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10109)
)
ORDER BY WOPK, TaskNo
now please check my output and error
please help to solve this issue. Thanks in Advance.
As noted in comments, use ELSE '' instead of ELSE ''''. The reason is that within a pair of single quotes, then '' tells SQL to escape a single quote into your output.
For instance, to show the output User's, you would need SELECT 'User''s'.

error- Each column has to have a unique name when you’re returning the query

I am trying to run reporting services with below SQL query
select ca.callingpartynumber, ca.originalcalledpartynumber, case
when calledpartylastname is not null then ca.calledpartylastname + ',' + calledpartyfirstname
else p1.name end,
p1.location, p1.dept, p1.title,
case
when callingpartylastname is not null then ca.callingpartylastname + ',' + callingpartyfirstname
else p3.name end
from calldata.calldetailreport ca
join ps_bc_peoplesource_base p1 on ca.originalcalledpartynumber = replace(p1.bc_int_phone, '-', '')
left outer join ps_bc_peoplesource_base p3 on ca.callingpartynumber = replace(p1.bc_int_phone, '-', '')
where originalcalledpartynumber in (select replace(bc_int_phone, '-', '') internal_modified from ps_bc_peoplesource_base where bc_lan_id = 'f7c')
--and datetimedisconnect between #startdate and #enddate --1221
I get this error-
“An item with the same key has already been added.”
You are missing Column Alias for Two Case Statement in Your SELECT query. As SSRS uses only the column name as the key, not table + column, so it was choking.
Refer Here And Here And Here also
SELECT ca.callingpartynumber, ca.originalcalledpartynumber,
CASE WHEN calledpartylastname IS NOT NULL
THEN ca.calledpartylastname + ',' + calledpartyfirstname
ELSE p1.name END AS calledpartylastname,
p1.location,
p1.dept,
p1.title,
CASE WHEN callingpartylastname IS NOT NULL
THEN ca.callingpartylastname + ',' + callingpartyfirstname
ELSE p3.name END AS callingpartylastname
...
...

How to remove first and last charcter if character is ',' of name in Sql query

I combine two column value with ',' using below query.
SELECT
RTRIM(LTRIM(REPLACE(
IsNull(tbl1 .Reason,'') + ',' + IsNull(tbl2.OtherReason,''),',' ,'')))
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Now issue is that it remove all ',' using above query and I want to just remove last and first ','.
I have combine two column. Now
if tbl1 .Reason is null then it display output as " ,tbl2.OtherReason " and if tbl2.OtherReason is null the output is "tbl1 .Reason,"
Before above query, I also try with below query:
SELECT
IsNull(tbl1.Reason,'') + ',' + IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Thanks,
HItesh
You can use a case in the middle to check if the values are null or not.
declare #a nvarchar(5)
,#b nvarchar(5)
set #a = 'abc'
set #b = null--'123'
select isnull(#a, '') + case when #a is not null and #b is not null then ',' else '' end + isnull(#b, '')
Try this:
SELECT
CASE
WHEN tbl1.Reason IS NULL
THEN
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE LTRIM(RTRIM(tb2.Reason))
END
ELSE tbl1.Reason +
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE ',' + LTRIM(RTRIM(tb2.Reason))
END
END
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
You can concatenate a comma to the first value in case that second value is not null :
SELECT
IsNull(tbl1.Reason + case when tbl2.OtherReason is null then '' else ',' end, '') +
IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId

SQL Removing Duplicate Result with Left Join

I've got code that if pulling info from two different tables, and I'm getting duplicates. I've tried DISTINCT in the SELECT statement, but I get lots of errors "ntext data type cannot be selected as DISTINCT because it is not comparable."
So my next attempt was to try GROUP BY, but I get errors "Column Person.Pers_FirstName is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
So my records have multiple relationship fields, but it's a problem because some records have none, one or more than one relationship (the options are NULL, project engineer, project owner, or project contractor). Current code only shows NULL and Project Engineer, but if there's records with the other two then they are excluded. If I include the other relationship descriptions then I get duplicates.
SELECT
RTRIM(ISNULL(Pers_FirstName, '')) + ' ' + RTRIM(ISNULL(Pers_LastName, '')) AS Pers_FullName,
RTRIM(ISNULL(oppocomp.Comp_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_PhoneNumber, '')) AS Comp_PhoneFullNumber,
RTRIM(ISNULL(oppocomp.Comp_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(oppocomp.Comp_FaxNumber, '')) AS Comp_FaxFullNumber,
RTRIM(ISNULL(Pers_PhoneCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_PhoneNumber, '')) AS Pers_PhoneFullNumber,
RTRIM(ISNULL(Pers_FaxCountryCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxAreaCode, '')) + ' ' + RTRIM(ISNULL(Pers_FaxNumber, '')) AS Pers_FaxFullNumber,
Opportunity.*, oppocomp.Comp_Name, oppocomp.Comp_Territory, oppocomp.Comp_EmailAddress,
oppocomp.Comp_CompanyId, oppocomp.Comp_SecTerr, oppocomp.Comp_CreatedBy,
oppocomp.Comp_PrimaryUserID, Terr_Caption, Pers_Title, Pers_EmailAddress, Pers_SecTerr,
Pers_CreatedBy, Pers_PersonId, Pers_PrimaryUserID, Chan_Description,
oppocomp.Comp_ChannelID, (Oppo_Base_Currency.Curr_CurrencyID) AS Oppo_WeightedForecast_CID,
Pers_ChannelID ((Oppo_Forecast / Oppo_Forecast_Currency.Curr_Rate) * Oppo_Certainty / 100) AS Oppo_WeightedForecast,
Oppo_PrimaryAccountId AS Acc_AccountId, rend_Notes, renl_description,
relcomp.Comp_Name AS Rela_CompanyName
FROM Opportunity
LEFT JOIN Person ON Oppo_PrimaryPersonID = Pers_PersonID
LEFT JOIN Company AS oppocomp ON Oppo_PrimaryCompanyID = Comp_CompanyId
LEFT JOIN Territories ON Oppo_SecTerr = Terr_TerritoryId
LEFT JOIN Channel ON Chan_ChannelId = Oppo_ChannelId
LEFT JOIN RelatedEntityData ON Oppo_OpportunityId = rend_entity1id
LEFT JOIN RelatedEntityLinks ON rend_relatedentitylinkid = REnL_RelatedEntityLinkID
LEFT JOIN Company AS relcomp ON rend_entity2id = relcomp.Comp_CompanyId
LEFT JOIN Currency Oppo_Forecast_Currency ON Oppo_Forecast_CID = Oppo_Forecast_Currency.Curr_CurrencyID
LEFT JOIN Currency Oppo_Base_Currency
ON Oppo_Base_Currency.Curr_CurrencyID = (
SELECT CAST(CAST(Parm_Value AS NCHAR) AS INTEGER)
FROM Custom_SysParams
WHERE Parm_Name = 'BaseCurrency'
)
WHERE Oppo_Deleted IS NULL
AND (renl_description IS NULL OR renl_description = 'Project Engineer')

Conditionals in transact-sql select column lists

I've got a query that looks a bit like this:
select
records.id,
contacts.name + ' (' + contacts.organization + ')' as contact,
from records
left join contacts on records.contact = contacts.contactid
Problem is - contacts.organization is frequently empty, and I get contacts like "John Smith ()". Is there a way to only concatenate the organization if it's non-empty?
Use a CASE statement
SELECT
records.id,
CASE contacts.organization
WHEN '' THEN contacts.name
ELSE contacts.name + ' (' + contacts.organization + ')'
END as Contact
FROM records
LEFT JOIN contacts ON records.contact = contacts.contactid
You could modify it to also check for NULL values, but I do not believe you have that issue because if you had a NULL in your contacts.organization, your entire result field would be null instead of blank.
Not sure if this is the best way to do it:
CASE contacts.organization
WHEN '' THEN ''
ELSE '(' + contacts.organzation + ')' END
use a CASE, like CASE WHEN contacts.organization not null then ' (' + c.o + ') ' else '' end
You always need to expect nulls, because of your outer join:
select
records.id,
contacts.name + CASE WHEN contacts.organization IS NULL OR contacts.organization='' THEN '' ELSE ' (' + contacts.organization + ')' END as contact,
from records
left join contacts on records.contact = contacts.contactid
If you're dealing with NULL values there are some functions that specialize in them which are worth knowing.
ISNULL()
COALESCE()
NULLIF()
NULLIF() might be the one you're looking for. It basically takes two params. It returns the first param unless it is NULL, otherwise it returns the second.
Here's what I approximate your code would be:
select
records.id,
contacts.name + ISNULL(' (' + contacts.organization + ')', '') as contact,
from records
left join contacts on records.contact = contacts.contactid
Most NULL-related functions can be replaced by a larger CASE statement. CASE is your more general tool. But using specific functions will make your code cleaner, or at least more terse.