Display multiple rows of fields into one row of multiple columns SQL - sql

I am trying to get output to display multiple fields of data; where some of the data is the same but added more than once, into one row. eg workflow for actions, some action_cds can be used more than once and with more than one outcome.
Select ContactNo, name, address, action_cd,
action_due_date, Action_outcome
from Table1 which holds the Contact Actions data joined with Table2 which holds other relevant fields for output report.
I apologise if that sounds confusing. Basically there is a workflow which has many actions depending on what needs to happen, some actions could be used more than once with different due dates and different outcomes.
All this is required to be displayed in one row per Contact_No / Property in a report.
I have got myself confused trying various things. Went back to CASE but no luck.
SELECT distinct(ct.contact_no) AS 'ContactNo',
CASE WHEN (action_no = '1') THEN ac.action_cd + ' - ' +rd.act_desn end AS Act1,
CASE WHEN (action_no = '1') THEN ac.action_due_dt end As Act1DueDate,
CASE WHEN (action_no = '1') THEN ac.completed_dt end AS Act1COMPLETEDDATE,
CASE WHEN (action_no = '1') THEN ao.outcome end AS Act1OUTCOME,
CASE WHEN (action_no = '1') THEN ac.comment end AS Act1Comment,
CASE WHEN (action_no = '1') THEN ac.order_no end AS Act1ORDERNO,
CASE WHEN (action_no = '2') THEN ac.action_cd + ' - ' +rd.act_desn end AS Act2,
CASE WHEN (action_no = '2') THEN ac.action_due_dt end As Act2DueDate,
CASE WHEN (action_no = '2') THEN ac.completed_dt end AS Act2COMPLETEDDATE,
CASE WHEN (action_no = '2') THEN ao.outcome end AS Act2OUTCOME,
CASE WHEN (action_no = '2') THEN ac.comment end AS Act2Comment,
CASE WHEN (action_no = '2') THEN ac.order_no end AS Act2ORDERNO,
CASE WHEN (action_no = '3') THEN ac.action_cd + ' - ' +rd.act_desn end AS Act3,
CASE WHEN (action_no = '3') THEN ac.action_due_dt end As Act3DueDate,
CASE WHEN (action_no = '3') THEN ac.completed_dt end AS Act3COMPLETEDDATE,
CASE WHEN (action_no = '3') THEN ao.outcome end AS Act3OUTCOME,
CASE WHEN (action_no = '3') THEN ac.comment end AS Act3Comment,
CASE WHEN (action_no = '3') THEN ac.order_no end AS Act3ORDERNO
FROM table1 as ac WITH (nolock)
left OUTER JOIN table2 as ct WITH (nolock) ON ac.comp_id = ct.comp_id AND ac.contact_no = ct.contact_no
LEFT OUTER JOIN table3 AS rd WITH (nolock) ON ac.action_cd = rd.action_cd
left outer join View1 as ao with (nolock) on ac.outcome_cd = ao.code_id

Related

How to use a calculated column to calculate another column in the same query using a subquery

I'm trying to add a new calculated field (TravelTime) based on the NLength and NSpeedLimit fields from the following query
SELECT
sc.OBJECTID,
sn.Name,
case when hn.side = 'Right Side' then ''
else sc.LCity
end as LCity,
case when hn.side = 'Left Side' then ''
else sc.RCity
end as RCity,
case when hn.side = 'Right Side' then ''
else sc.LZip
end as LZip,
case when hn.side = 'Left Side' then ''
else sc.RZip
end as RZip,
sc.SHAPE.STLength() AS NLength,
ISNULL(sc.SpeedLimit,1) AS NSpeedLimit
FROM STREETNAME AS sn
INNER JOIN
STREETHASSTREETNAME AS hn ON
sn.GlobalID = hn.GlobalID AND
hn.Role = 'Primary'
INNER JOIN STREETCENTERLINE AS sc ON
hn.GlobalID = sc.GlobalID
The new calculated field is TravelTime = NLength/(NSpeedLimit*88)
but I can't add NLength/(NSpeedLimit*88) AS TravelTimein the select statement. I know I need to do a subquery but I don't know where it's supposed to go.
You can use Temp_tables, Derived tables or Common table expressions (CTE) to obtain the result. Simple approach would be Derived table as you dont need much more coding.
SELECT A.*
, A.NLength/(A.NSpeedLimit * 88) as [TravelTime]
FROM
(
SELECT
sc.OBJECTID,
sn.Name,
case when hn.side = 'Right Side' then ''
else sc.LCity
end as LCity,
case when hn.side = 'Left Side' then ''
else sc.RCity
end as RCity,
case when hn.side = 'Right Side' then ''
else sc.LZip
end as LZip,
case when hn.side = 'Left Side' then ''
else sc.RZip
end as RZip,
sc.SHAPE.STLength() AS NLength,
ISNULL(sc.SpeedLimit,1) AS NSpeedLimit
FROM STREETNAME AS sn
INNER JOIN
STREETHASSTREETNAME AS hn ON
sn.GlobalID = hn.GlobalID AND
hn.Role = 'Primary'
INNER JOIN STREETCENTERLINE AS sc ON
hn.GlobalID = sc.GlobalID
) AS A
You can add the columns in the FROM clause using apply:
SELECT . . .
v.NLength, v.NSpeedLimit,
(v.NLength / (v.NSpeedLimit*88)) as TravelTime
FROM STREETNAME sn JOIN
STREETHASSTREETNAME hn
ON sn.GlobalID = hn.GlobalID AND
hn.Role = 'Primary' JOIN
STREETCENTERLINE sc
ON hn.GlobalID = sc.GlobalID CROSS APPLY
(VALUES (sc.SHAPE.STLength(), COALESCE(sc.SpeedLimit, 1)
) v(NLength, NSpeedLimit)

How to use bitwise operator in existing sql query?

Here is my sql query. I have column name "ExpenseBucketCoverage" in claim table in which I am storing bitwise operators store multiple values in one column like below
MED_COPAY = 1, MED_DED= 10, MED_COINS = 100, RX_COPAY = 1, RX_DED= 10, RX_COINS = 100
I want to replace hard coded value like MED_COPAY, MED_COINS, MED_DED, RX_DED, RX_COINS & RX_COPAY in query by using ExpenseBucketCoverage column value. Can some one please tell me how can I do that?
Someone has suggested me below soultion
retrieve data from claim and left joining the first matched record in eligibility. And then add custom code to loop through the datarows to split the rows by covered expense bucket, and set the service category code in-memory column based on the ExpenseBucketCoverage value for the claim.
SELECT
e.categoryid,
c.servicetype,
'II' AS RepordType,
e.TPAId AS TPA_Id,
e.EmployerCode,
e.SubscriberId,
e.MemberID,
c.ServiceFrom,
c.ServiceTo,
CASE
WHEN e.categoryid IN( 'MED_DED', 'RX_DED' ) THEN
deductible
WHEN e.categoryid IN( 'MED_COINS', 'RX_COINS' ) THEN
isnull(coins,0)
WHEN e.categoryid IN( 'MED_COPAY', 'RX_COPAY' ) THEN
copay
ELSE 0
END AS ClaimAmount,
'' AS AccountTypeCode,
'1' ClaimsCrossoverAutoPay,
e.CategoryId,
CASE c.ServiceType
WHEN 'H' THEN
CASE e.PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS PayProvider,
CASE c.ServiceType
WHEN 'H' THEN
CASE PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS ReimbursementMethod,
CASE c.ServiceType
WHEN 'H' THEN c.Provider
WHEN 'P' THEN ''
END AS ProviderId,
'1' EnforceAccountEffectiveDates,
c.Id,
c.ClaimNumber + e.CategoryId as 'ExternalClaimNumber',
c.ProviderName,
c.CarrierId + ';' + c.SourceClaimNumber AS Notes
FROM Claim c
INNER JOIN Eligibility e ON e.TPAId = c.TPAId AND e.EIN = c.EIN AND
c.Processed = 'Y' AND e.FilterType = 'Eligibility'
AND c.TPAId='PrimePay'
AND (c.ServiceFrom >= e.BenefitEffectiveDate
AND c.ServiceFrom <=e.BenefitTermDate)
AND ( ( c.PayorID = c.PatientSSN
AND e.SubscriberSSN = c.PatientSSN
AND (c.EmployeeFirstName = c.PatientFirstName
AND c.EmployeeLastName = c.PatientLastName)
AND(e.MemberSSN = '' OR e.MemberSSN = NULL)
AND(e.MemberFirstName = '' OR e.MemberFirstName = NULL)
AND(e.MemberLastName = '' OR e.MemberLastName = NULL))
OR((c.PayorID != c.PatientSSN AND e.MemberSSN = c.PatientSSN
AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName = c.PatientLastName)
OR(c.PayorID != c.PatientSSN AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName= c.PatientLastName)))
AND (( c.Servicetype ='P'
AND e.CategoryID IN('RX_COINS','RX_COPAY', 'RX_DED' ))
OR ( c.Servicetype = 'H'
AND e.CategoryID IN( 'MED_COINS','MED_COPAY', 'MED_DED' )))

Performance Issue in Select groupby

I have following block of code and It takes approx 4-5 minutes to execute. All the tables in this block has large amount of data.
Select
spa.Student_Id,
Cast(Case When ISNULL(#PeriodNumbers, '') = '' Then --PeriodCode Come
CPS.PeriodIdentifier
Else --period number come
Cast(SPA.PeriodNumber as varchar)
End As varchar) As Period,
IsNULL(Count(*), 0) As TotalCount,
AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar) As PeriodNumber
From
(Select Student_ID
From OpenXml(#Handle,'/NewDataSet/Table', 2)
With (Student_ID int) As DT
) FilterDT
Inner Join
dbo.StudentPeriodicAttendanceArchive SPA WITH(NOLOCK) On FilterDT.Student_ID = SPA.Student_ID
Inner Join
dbo.AcademicYear AY WITH(NOLOCK) On AY.AYIdentifier = #AYIdentifier
And AY.School_Domain = #School_Domain
Inner join
dbo.CPsession CPS WITH(NOLOCK) On CPS.SSEC_ID = SPA.SSEC_ID
And CPS.PeriodNumber= spa.periodnumber
And CPS.School_Domain = #School_Domain
And CPS.AYIdentifier = #AYIdentifier
And (CPS.CPSDelStatus = 0 Or CPS.CPSDelStatus Is Null)
Inner Join
dbo.BellTimingScheduleStructure BTSS WITH(NOLOCK) ON BTSS.DayNumber = CPS.WD_ID
And BTSS.SchedulingWeek = CPS.Week
Inner Join
dbo.ClassPeriods CP WITH(NOLOCK) On CP.CP_Id = CPS.CP_ID
And BTSS.CPR_ID = CP.CPR_ID
And BTSS.WeekDay = Case When BTSS.CPRType='D' Then BTSS.WeekDay Else CP.WD_ID End
And BTSS.DayNumber = Case When BTSS.CPRType='D' Then CP.WD_ID Else BTSS.DayNumber End
And BTSS.SchedulingWeek = Case When BTSS.CPRType='W' Then BTSS.SchedulingWeek Else CP.Week End
And BTSS.DateItem = SPA.Attdate
And CP.CPDelStatus = '0'
And IsNull(CP.IsLocked, '0') = '0'
Inner Join
dbo.AttendanceCodes AC WITH(NOLOCK) On AC.AC_ID = SPA.AttCode_ID
Where
SPA.School_Domain = #School_Domain
And AttDate >= Case When #IsYearLongTotals=1 then AY.AYStartDate Else #ActualStartDate End
And AttDate <= Case When #IsYearLongTotals=1 then AY.AYEndDate Else #ActualEndDate End
And IsNull(#Subject_ID, -1) = Case When IsNull(#Subject_ID, -1) <> -1
Then CPS.Subject_ID
Else IsNull(#Subject_ID, -1)
End
Group By
spa.Student_ID,
Cast(Case When ISNULL(#PeriodNumbers, '') = ''
Then CPS.PeriodIdentifier
Else
Cast(SPA.PeriodNumber as varchar)
End As varchar), AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar)
I have a table StudentPeriodicAttendanceArchive which contains attendance information. I want to calculate total present and absent count.
Please suggest what should I do to improve the performance. I am using SQL Server 2008 R2

Duplication issue with left join only by adding one column

So I apologize for the wall of code, but I'm losing my mind over this tiny issue that is kicking my butt. The below query works perfectly and gives me everything I need to see with the exception of one column from DB.ACTIVITY_T. The moment I add said column, I immediately get duplicates where there is a MNT.ARRIVEDTS present. I can't seem to figure out why adding one more column to my select statement is causing this duplication. Maybe I'm too deep into this to see what's right in front of me? If you see what could be causing the error, please feel free to enlighten me.
SELECT
TRIM(B.REFNUMBER) AS "REFNUMBER"
,DATE(NUM_TSTAMP) AS "P/U DATE"
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END AS "DELIVERY DATE"
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END AS "DELIVERED"
,B.WEIGHT AS "WGT"
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE) AS "SHPMNT CUBE"
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END AS "DERP POINT"
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO) END AS "DERP #"
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END AS "SEQUENCE"
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END AS "DERP DERP"
,DATE(E.EVENT_TIMESTAMP) AS "DERP DATE"
,TIME(E.EVENT_TIMESTAMP) AS "DERP TIME"
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END AS "DERP
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END AS "DERP CUBE”
,MNT."DERP ARRIVED"
FROM PQ.MAIN B
INNER JOIN PQ.MAIN_ALTERNATE A
ON B.REFNUMBER = A.REFNUMBER
AND B.CORRECTION = A.CORRECTION
AND A.NUMBER_KEY = ''
INNER JOIN PQ.MAIN_NAME C
ON C.REFNUMBER = B.REFNUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'
AND C.NUMBER_KEY = ''
AND C.NUM_CODE = 'ABCD'
INNER JOIN PQ.MAIN_NAME S
ON B.REFNUMBER = S.REFNUMBER
AND B.CORRECTION = S.CORRECTION
AND S.TYPE = 'S'
AND S.COUNTRY = 'US'
AND S.NUMBER_KEY = ''
LEFT OUTER JOIN DB.ACTIVITY_NUM MN
ON MN.REFNUMBER = B.REFNUMBER
LEFT OUTER JOIN (SELECT MAX(DATE(A.ARRIVEDTS)) AS "DERP ARRIVED", MFSTNBR
FROM AF.MANIFEST_T A WHERE A.DESTINATION IN ('1234','5647') GROUP BY MFSTNBR) AS MNT
ON MNT.MFSTNBR = MN.MFSTNBR
LEFT OUTER JOIN PQ.MAIN_EVENT E
ON E.REFNUMBER = B.REFNUMBER
AND E.EVENT_TYPE = 'R'
AND E.EVENT_DESCRIPTION = 'RANDO'
AND E.NUMBER_KEY = ''
LEFT OUTER JOIN DB.DERP_INDEX I
ON B.REFNUMBER = I.REFNUMBER
AND I.DOC_TYPE = 'LIE'
AND PAGE_NUM = '1'
AND I.INDEX_DATE >= CURRENT DATE - 15 DAYS
LEFT OUTER JOIN PQ.MAIN_REFNO R
ON R.REFNUMBER = B.REFNUMBER
AND R.CORRECTION = B.CORRECTION
AND REFNO LIKE '%BOOG%'
AND R.NUMBER_KEY = ''
WHERE B.NUM_NUM_NUM = '123'
AND B.DESTINATION IN ('1234','5647','9856')
AND DATE(B.NUM_TSTAMP) >= CURRENT DATE - 10 DAYS
GROUP BY
TRIM(B.REFNUMBER)
,DATE(NUM_TSTAMP)
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END
,B.WEIGHT
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE)
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO)
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END
,DATE(E.EVENT_TIMESTAMP)
,TIME(E.EVENT_TIMESTAMP)
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END
,MNT."DERP ARRIVED"
Here are the results that you asked for.
REFNUMBER DERP ARRIVED MFSTNBR
123456789 [null] [null]
123456789 [null] [null]
123456789 2015-12-15 32304587
987654321 [null] [null]
987654321 [null] [null]
987654321 2015-12-13 49304483
Each null actually has a different MFSTNBR tied to it, but it's returning a null because it doesn't meet the '1234' or '5647' criteria. If I remove the destination criteria the nulls would be replaced with similar but different MFSTNBR.
My guess is you're getting multiple records from MNT when you only want one...
Likely MNT.Destination having 2 different values will result in 2 records for the max, not one.
Replace the
LEFT OUTER JOIN DB.ACTIVITY_T MNT
with
(SELECT MAX(DATE(MNT.ARRIVEDTS)) as "DERP ARRIVED", MFSTNBR
FROM DB.Activity_T
WHERE MNT.DESTINATION IN ('1234','5647')
GROUP BY MFSTNBR) as MNT
and eliminate the join critiera;
ND MNT.DESTINATION IN ('1234','5647') as it's taken care of by the inline view.
oh and modify the select to just look for "DERP ARRIVED" on the top most select.
Just my guess...
SELECT
TRIM(B.REFNUMBER) AS "REFNUMBER"
,DATE(NUM_TSTAMP) AS "P/U DATE"
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END AS "DELIVERY DATE"
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END AS "DELIVERED"
,B.WEIGHT AS "WGT"
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE) AS "SHPMNT CUBE"
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END AS "DERP POINT"
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO) END AS "DERP #"
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END AS "SEQUENCE"
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END AS "DERP DERP"
,DATE(E.EVENT_TIMESTAMP) AS "DERP DATE"
,TIME(E.EVENT_TIMESTAMP) AS "DERP TIME"
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END AS "DERP
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END AS "DERP CUBE”
-------Modified the next line--------------
,MNT."DERP ARRIVED"
FROM PQ.MAIN B
INNER JOIN PQ.MAIN_ALTERNATE A
ON B.REFNUMBER = A.REFNUMBER
AND B.CORRECTION = A.CORRECTION
AND A.NUMBER_KEY = ''
INNER JOIN PQ.MAIN_NAME C
ON C.REFNUMBER = B.REFNUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'
AND C.NUMBER_KEY = ''
AND C.NUM_CODE = 'ABCD'
INNER JOIN PQ.MAIN_NAME S
ON B.REFNUMBER = S.REFNUMBER
AND B.CORRECTION = S.CORRECTION
AND S.TYPE = 'S'
AND S.COUNTRY = 'US'
AND S.NUMBER_KEY = ''
LEFT OUTER JOIN DB.ACTIVITY_NUM MN
ON MN.REFNUMBER = B.REFNUMBER
-------Modified the next line--------------
LEFT OUTER JOIN (SELECT MAX(DATE(A.ARRIVEDTS)) as "DERP ARRIVED", MFSTNBR
FROM DB.Activity_T A
WHERE A.DESTINATION IN ('1234','5647')
GROUP BY MFSTNBR) as MNT
ON MNT.MFSTNBR = MN.MFSTNBR
-------Removed this line. the next line--------------
---and MNT.DESTINATION IN ('1234','5647') -------
LEFT OUTER JOIN PQ.MAIN_EVENT E
ON E.REFNUMBER = B.REFNUMBER
AND E.EVENT_TYPE = 'R'
AND E.EVENT_DESCRIPTION = 'RANDO'
AND E.NUMBER_KEY = ''
LEFT OUTER JOIN DB.DERP_INDEX I
ON B.REFNUMBER = I.REFNUMBER
AND I.DOC_TYPE = 'LIE'
AND PAGE_NUM = '1'
AND I.INDEX_DATE >= CURRENT DATE - 15 DAYS
LEFT OUTER JOIN PQ.MAIN_REFNO R
ON R.REFNUMBER = B.REFNUMBER
AND R.CORRECTION = B.CORRECTION
AND REFNO LIKE '%BOOG%'
AND R.NUMBER_KEY = ''
WHERE B.NUM_NUM_NUM = '123'
AND B.DESTINATION IN ('1234','5647','9856')
AND DATE(B.NUM_TSTAMP) >= CURRENT DATE - 10 DAYS
GROUP BY
TRIM(B.REFNUMBER)
,DATE(NUM_TSTAMP)
,REPORT_TS
,REPORT_TS
,B.WEIGHT
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE)
,B.DESTINATION
,R.REFNO
,C.CITY
,E.EVENT_DESCRIPTION
,DATE(E.EVENT_TIMESTAMP)
,TIME(E.EVENT_TIMESTAMP)
,I.DOC_TYPE
,B.CUBE
--- Added this line----
,MNT."DERP ARRIVED"

SQL Set Column Equal to Value

I have the following query. I need Description to be set to the value of the long statement in the middle - the part beginning with CONVERT and ending with [Description]. The query I have now runs but the value of Description in the result is always NULL. Any ideas?
select s.SectionId,
s.Academic_Year [AcademicYear],
s.Academic_Term [AcademicTerm],
s.Academic_Session [AcademicSession],
s.Event_Id [EventId],
s.Event_Sub_Type [EventSubType],
s.Section [Section],
s.Event_Long_Name [EventLongName],
e.Description [EventDescription],
CONVERT(varchar(MAX), S.DESCRIPTION)
+ '<br /><br /><a href="http://www.bkstr.com/webapp/wcs/stores/servlet/booklookServlet?bookstore_id-1=044&term_id-1='
+ CASE S.ACADEMIC_TERM
WHEN 'SPRING' THEN 'SPRING'
WHEN 'SUMMER' THEN 'SUM'
WHEN 'FALL' THEN 'FALL'
WHEN 'J TERM' THEN 'J TERM'
ELSE 'ADV'
END
+ S.ACADEMIC_YEAR + '/' +
CASE S.ACADEMIC_SESSION
WHEN '01' THEN '1'
WHEN '02' THEN '2'
WHEN '03' THEN '3'
END
+ '&div-1=HILB&dept-1=' + SUBSTRING(S.EVENT_ID, 1, CHARINDEX(' ', S.EVENT_ID) - 1) + '&course-1=' + SUBSTRING(S.EVENT_ID, CHARINDEX(' ', S.EVENT_ID) + 1,
LEN(S.EVENT_ID)) + '&section-1=' + CONVERT(varchar(2), S.SECTION) + '" target=' + '"_blank">View Book Information</a>' [Description],
cest.Medium_Desc [SubTypeDescription],
s.Credits [Credits],
cge.Medium_Desc [GeneralEd],
s.Start_Date [StartDate],
s.End_Date [EndDate],
s.Max_Participant [MaximumParticipants],
s.Adds [AddCount],
s.Wait_List [WaitlistCount],
s.Sec_Enroll_Status [EnrollmentStatus],
o.Org_Name_1 [CampusName],
cp.Medium_Desc [ProgramDescription],
cc.Medium_Desc [CollegeDescription],
cd.Medium_Desc [DepartmentDescription],
ccm.Medium_Desc [CurriculumDescription],
ccl.Medium_Desc [ClassLevelDescription],
nt.Nontrad_Med_Name [NonTraditionalDescription],
cpn.Medium_Desc [PopulationDescription],
case s.Other_Org when 'N' then 0 else s.Other_Org_Part end as [CampusOtherLimit],
case s.Other_Program when 'N' then 0 else s.Other_Program_Part end as [ProgramOtherLimit],
case s.Other_College when 'N' then 0 else s.Other_College_Part end as [CollegeOtherLimit],
case s.Other_Department when 'N' then 0 else s.Other_Dept_Part end as [DepartmentOtherLimit],
case s.Other_Curriculum when 'N' then 0 else s.Other_Curric_Part end as [CurriculumOtherLimit],
case s.Other_Class_Level when 'N' then 0 else s.Other_CLevel_Part end as [ClassLevelOtherLimit],
case s.Other_NonTrad when 'N' then 0 else s.Other_NonTrad_Part end as [NonTraditionalOtherLimit],
case s.Other_Population when 'N' then 0 else s.Other_Pop_Part end as [PopulationOtherLimit],
s.Other_Org_Add as [CampusOtherRegistered],
s.Other_Program_Add as [ProgramOtherRegistered],
s.Other_College_Add as [CollegeOtherRegistered],
s.Other_Dept_Add as [DepartmentOtherRegistered],
s.Other_Curr_Add as [CurriculumOtherRegistered],
s.Other_CLevel_Add as [ClassLevelOtherRegistered],
s.Other_Nontrad_Add as [NonTraditionalOtherRegistered],
s.Other_Pop_Add as [PopulationOtherRegistered],
case s.Registration_Type when 'TRAD' then 0 else 1 end as [IsConEd],
cat.Medium_Desc [TermDescription],
cas.Medium_Desc [SessionDescription],
s.Credit_Type [DefaultCreditType],
cct.Medium_Desc [CreditTypeDescription]
from sections s
left join code_eventsubtype cest on cest.code_value_key = s.event_sub_type
left join code_generaled cge on cge.code_value_key = s.general_ed
left join event e on e.event_id = s.event_id
left join organization o on o.org_code_id = s.org_code_id
left join code_program cp on cp.code_value_key = s.program
left join code_college cc on cc.code_value_key = s.college
left join code_department cd on cd.code_value_key = s.department
left join code_curriculum ccm on ccm.code_value_key = s.curriculum
left join code_classlevel ccl on ccl.code_value_key = s.class_level
left join nontraditional nt on nt.nontrad_program = s.nontrad_program
left join code_population cpn on cpn.code_value_key = s.population
left join code_acaterm cat on cat.code_value_key = s.academic_term
left join code_acasession cas on cas.code_value_key = s.academic_session
left join code_acacredittype cct on cct.code_value_key = s.credit_type
One of your inputs must be NULL.
You can probably solve this by identifying which it is and using COALESCE or ISNULL:
COALESCE(x, '')
ISNULL(x, '')
COALESCE is the standard ANSI way, ISNULL gives slightly better performance (although the difference is probably insignificant in most cases).