SQL Set Column Equal to Value - sql

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).

Related

CREATE VIEW IN DB2

I have a DB2 SQL statement which selects the required rows successfully. Since its a time consuming query, I am trying to convert it into a view using the create view statement.
WITH firstequiprrn
AS (SELECT oeord# equiporder,
Min(RRN(a)) firstrow
FROM iesqafile.OPEQUIP a
GROUP BY oeord#
ORDER BY 1),
firstequiprow
AS (SELECT oeord#,
oetrlr equipmentnumber
FROM firstequiprrn
INNER JOIN iesqafile.OPEQUIP b
ON equiporder = oeord#
AND firstrow = RRN(b)),
ordermiles
AS (SELECT mmord#,
mmtotal
FROM iesqafile.mmiles
WHERE mmord# IN(SELECT orodr#
FROM iesqafile.order)
AND mmrectype = 'O'
AND mmdsp# = '00'),
stopgroup
AS (SELECT soord stoporder,
COUNT(*) stopsremain,
Min(sostp#) nextstop,
Max(soappr) apptreq,
Max(soaptm) apptmade
FROM iesqafile.stopoff
INNER JOIN iesqafile.order
ON orodr# = soord
WHERE soardt = 0
GROUP BY soord
ORDER BY 1) SELECT a.orodr# orodr_,
orcust,
orldat,
CASE orpdat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orpdat), 'YYYY-MM-DD')
END erdat2,
CASE orptim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(orptim, 1, 2), ':'),
SUBSTRING(orptim, 3, 4))
END AS ertim2,
CASE orapdt
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orapdt), 'YYYY-MM-DD')
END ltdat2,
CASE oraptm
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(oraptm, 1, 2), ':'),
SUBSTRING(oraptm, 3, 4))
END AS lttim2,
CASE orddat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orddat), 'YYYY-MM-DD')
END dldat2,
CASE ordtim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(ordtim, 1, 2), ':'),
SUBSTRING(ordtim, 3, 4))
END AS dltim2,
orestr,
a.ordv# ordv_,
orcons,
oreqty,
orspec,
a.orstp# orstp_,
orcomc,
( CASE
WHEN mmtotal IS NOT NULL THEN mmtotal
ELSE 0
END ) mmtotal,
orwgt,
orocty,
orost,
ordcty,
ordst,
orara asarea,
orpdrv oprdrv,
orld# orld_,
ordsp# ordsp_,
orshdt,
orshtm,
ornwpk,
( CASE
WHEN equipmentnumber IS NOT NULL THEN equipmentnumber
ELSE ''
END ) EquipmentNumber,
( CASE
WHEN apptreq IS NOT NULL THEN apptreq
ELSE 'N'
END ) apptreq,
( CASE
WHEN apptmade IS NOT NULL THEN apptmade
ELSE 'N'
END ) apptmade,
( CASE
WHEN ununit IS NOT NULL THEN ununit
ELSE ' '
END ) UNUNIT,
( CASE
WHEN unsupr IS NOT NULL THEN unsupr
ELSE ' '
END ) asdrmgr,
( CASE
WHEN unfmgr IS NOT NULL THEN unfmgr
ELSE ' '
END ) asflmgr,
( CASE
WHEN untrl1 IS NOT NULL THEN untrl1
ELSE ' '
END ) UNTRL1
FROM iesqafile.order a
LEFT OUTER JOIN ordermiles
ON mmord# = a.orodr#
LEFT OUTER JOIN firstequiprow
ON a.orodr# = oeord#
LEFT OUTER JOIN stopgroup
ON a.orodr# = stoporder
LEFT OUTER JOIN iesqafile.units
ON ununit = a.orpdrv
WHERE orld# <> ordsp#
AND ( orspec = 'N# C'
OR orspec = 'N# P' )
AND orpdrv <> ''
AND orpdat >= 2018001
UNION
SELECT d.orodr# as ordddd,
orcust,
orldat,
CASE orpdat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orpdat), 'YYYY-MM-DD')
END erdat2,
CASE orptim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(orptim, 1, 2), ':'),
SUBSTRING(orptim, 3, 4))
END AS ertim2,
CASE orapdt
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orapdt), 'YYYY-MM-DD')
END ltdat2,
CASE oraptm
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(oraptm, 1, 2), ':'),
SUBSTRING(oraptm, 3, 4))
END AS lttim2,
CASE orddat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orddat), 'YYYY-MM-DD')
END dldat2,
CASE ordtim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(ordtim, 1, 2), ':'),
SUBSTRING(ordtim, 3, 4))
END AS dltim2,
orestr,
ordv#,
orcons,
oreqty,
orspec,
orstp#,
orcomc,
( CASE
WHEN mmtotal IS NOT NULL THEN mmtotal
ELSE 0
END ) mmtotal,
orwgt,
orocty,
orost,
ordcty,
ordst,
orara,
orpdrv,
orld#,
ordsp#,
orshdt,
orshtm,
ornwpk,
( CASE
WHEN equipmentnumber IS NOT NULL THEN equipmentnumber
ELSE ' '
END ) EquipmentNumber,
( CASE
WHEN apptreq IS NOT NULL THEN apptreq
ELSE 'N'
END ) apptreq,
( CASE
WHEN apptmade IS NOT NULL THEN apptmade
ELSE 'N'
END ) apptmade,
( CASE
WHEN ununit IS NOT NULL THEN ununit
ELSE ' '
END ) UNUNIT,
( CASE
WHEN unsupr IS NOT NULL THEN unsupr
ELSE ' '
END ) UNSUPR,
( CASE
WHEN unfmgr IS NOT NULL THEN unfmgr
ELSE ' '
END ) UNFMGR,
( CASE
WHEN untrl1 IS NOT NULL THEN untrl1
ELSE ' '
END ) UNTRL1
FROM iesqafile.opplan
LEFT OUTER JOIN iesqafile.order d
ON d.orodr# = opord#
LEFT OUTER JOIN ordermiles
ON mmord# = d.orodr#
LEFT OUTER JOIN firstequiprow
ON d.orodr# = oeord#
LEFT OUTER JOIN stopgroup
ON d.orodr# = stoporder
LEFT OUTER JOIN iesqafile.units
ON ununit = d.orpdrv
So my first attempt to create the view was simply to add a CREATE VIEW AS at the beginning of the first statement. This resulted in the error below:
A column list must be specified because the result columns are unnamed.
I am failing to understand this error as the column headings are indeed specified as the select works without issues. All columns are displayed with appropriate headings.
However I tried to modify the query by adding the below instead of the simple create view.
create view pavt.v1 (v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16,v17,v18,v19,v20,v21,v22,v23,v24,v25,v26,v27,v28,v29,v30,v31,v32,v33,v34,v35,v36) as
This seemed to have worked and the view was created in library PAVT. However when I run a select on the view, I get an aritmetic overflow error with DB2 error code of -802.
I dont understand this as I am able to view the results but the issue comes only while attempting to create the query. Can somebody guide please?
A more detailed error description is below:
Message . . . . : Select or omit error on field
Cast(Translate(ORDER_14.ORPTIM, *UNNAMED Table) AS member V.
Cause . . . . . : A select or omit error occurred in record 0, record format
*FIRST, member number 1 of file V in library PAVT, because of condition 1 of
the following conditions:
1 - The data was not valid in a decimal field.
At this moment what I really want to know is if the method I am following to create the view is correct (atleast as far as the syntax goes). Maybe the error I am seeing is a data error?
Edit-1:
create view pavt.CCC1 as
WITH firstequiprrn
AS (SELECT oeord# equiporder,
Min(RRN(a)) firstrow
FROM iesqafile.OPEQUIP a
GROUP BY oeord#
ORDER BY 1),
firstequiprow
AS (SELECT oeord#,
oetrlr equipmentnumber
FROM firstequiprrn
INNER JOIN iesqafile.OPEQUIP b
ON equiporder = oeord#
AND firstrow = RRN(b)),
ordermiles
AS (SELECT mmord#,
mmtotal
FROM iesqafile.mmiles
WHERE mmord# IN(SELECT orodr#
FROM iesqafile.order)
AND mmrectype = 'O'
AND mmdsp# = '00'),
stopgroup
AS (SELECT soord stoporder,
COUNT(*) stopsremain,
Min(sostp#) nextstop,
Max(soappr) apptreq,
Max(soaptm) apptmade
FROM iesqafile.stopoff
INNER JOIN iesqafile.order
ON orodr# = soord
WHERE soardt = 0
GROUP BY soord
ORDER BY 1) SELECT a.orodr# orodr_,
orcust,
orldat,
CASE orpdat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orpdat), 'YYYY-MM-DD')
END erdat2,
CASE orptim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(char(orptim), 1, 2), ':'),
SUBSTRING(char(orptim), 3, 4))
END AS ertim2,
CASE orapdt
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orapdt), 'YYYY-MM-DD')
END ltdat2,
CASE oraptm
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(oraptm, 1, 2), ':'),
SUBSTRING(oraptm, 3, 4))
END AS lttim2,
CASE orddat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orddat), 'YYYY-MM-DD')
END dldat2,
CASE ordtim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(ordtim, 1, 2), ':'),
SUBSTRING(ordtim, 3, 4))
END AS dltim2,
orestr,
a.ordv# ordv_,
orcons,
oreqty,
orspec,
a.orstp# orstp_,
orcomc,
( CASE
WHEN mmtotal IS NOT NULL THEN mmtotal
ELSE 0
END ) mmtotal,
orwgt,
orocty,
orost,
ordcty,
ordst,
orara asarea,
orpdrv oprdrv,
orld# orld_,
ordsp# ordsp_,
orshdt,
orshtm,
ornwpk,
( CASE
WHEN equipmentnumber IS NOT NULL THEN equipmentnumber
ELSE ''
END ) EquipmentNumber,
( CASE
WHEN apptreq IS NOT NULL THEN apptreq
ELSE 'N'
END ) apptreq,
( CASE
WHEN apptmade IS NOT NULL THEN apptmade
ELSE 'N'
END ) apptmade,
( CASE
WHEN ununit IS NOT NULL THEN ununit
ELSE ' '
END ) UNUNIT,
( CASE
WHEN unsupr IS NOT NULL THEN unsupr
ELSE ' '
END ) asdrmgr,
( CASE
WHEN unfmgr IS NOT NULL THEN unfmgr
ELSE ' '
END ) asflmgr,
( CASE
WHEN untrl1 IS NOT NULL THEN untrl1
ELSE ' '
END ) UNTRL1
FROM iesqafile.order a
LEFT OUTER JOIN ordermiles
ON mmord# = a.orodr#
LEFT OUTER JOIN firstequiprow
ON a.orodr# = oeord#
LEFT OUTER JOIN stopgroup
ON a.orodr# = stoporder
LEFT OUTER JOIN iesqafile.units
ON ununit = a.orpdrv
WHERE orld# <> ordsp#
AND ( orspec = 'N# C'
OR orspec = 'N# P' )
AND orpdrv <> ''
AND orpdat >= 2018001
UNION
SELECT d.orodr# orodr_,
orcust,
orldat,
CASE orpdat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orpdat), 'YYYY-MM-DD')
END erdat2,
CASE orptim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(char(orptim), 1, 2), ':'),
SUBSTRING(char(orptim), 3, 4))
END AS ertim2,
CASE orapdt
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orapdt), 'YYYY-MM-DD')
END ltdat2,
CASE oraptm
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(oraptm, 1, 2), ':'),
SUBSTRING(oraptm, 3, 4))
END AS lttim2,
CASE orddat
WHEN 0 THEN Varchar(0)
ELSE Varchar_format(CHAR(orddat), 'YYYY-MM-DD')
END dldat2,
CASE ordtim
WHEN 0 THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(ordtim, 1, 2), ':'),
SUBSTRING(ordtim, 3, 4))
END AS dltim2,
orestr,
ordv# ordv_,
orcons,
oreqty,
orspec,
orstp# orstp_,
orcomc,
( CASE
WHEN mmtotal IS NOT NULL THEN mmtotal
ELSE 0
END ) mmtotal,
orwgt,
orocty,
orost,
ordcty,
ordst,
orara asarea,
orpdrv oprdrv,
orld# orld_,
ordsp# ordsp_,
orshdt,
orshtm,
ornwpk,
( CASE
WHEN equipmentnumber IS NOT NULL THEN equipmentnumber
ELSE ' '
END ) EquipmentNumber,
( CASE
WHEN apptreq IS NOT NULL THEN apptreq
ELSE 'N'
END ) apptreq,
( CASE
WHEN apptmade IS NOT NULL THEN apptmade
ELSE 'N'
END ) apptmade,
( CASE
WHEN ununit IS NOT NULL THEN ununit
ELSE ' '
END ) UNUNIT,
( CASE
WHEN unsupr IS NOT NULL THEN unsupr
ELSE ' '
END ) asdrmgr,
( CASE
WHEN unfmgr IS NOT NULL THEN unfmgr
ELSE ' '
END ) asflmgr,
( CASE
WHEN untrl1 IS NOT NULL THEN untrl1
ELSE ' '
END ) UNTRL1
FROM iesqafile.opplan
LEFT OUTER JOIN iesqafile.order d
ON d.orodr# = opord#
LEFT OUTER JOIN ordermiles
ON mmord# = d.orodr#
LEFT OUTER JOIN firstequiprow
ON d.orodr# = oeord#
LEFT OUTER JOIN stopgroup
ON d.orodr# = stoporder
LEFT OUTER JOIN iesqafile.units
ON ununit = d.orpdrv
The first error is because in your 2 main SELECT statements (being UNIONed together) you have different column names - so the View doesn't know what to call them and is requiring you to explicitly name them e.g. the first column in each statement:
SELECT a.orodr# orodr_ ...
SELECT d.orodr# as ordddd ...
For the 2nd error, what is the datatype of the ORPTIM column?
I'm guessing that this type of construct is causing the issue:
CASE orptim
WHEN 0
THEN Varchar(0)
ELSE CONCAT(CONCAT(SUBSTRING(orptim, 1, 2), ':'), SUBSTRING(orptim, 3, 4))
If orptim is a number/decimal then "WHEN 0" will work but "SUBSTRING(orptim, 1, 2)" won't - as you can't substring a number. If orptim is a string then "WHEN 0" w=may be casuing problems.

Issue with complex query "the multi-part identifier could not be bound"

I am having trouble creating this view on SQL. As a query, it runs fine, but when trying to save it as a view, it gives me the "the multi-part identifier could not be bound" error. I think it has something to do with implicit joins.
The issue occurs when inserting the part with the extra tabs in the script below (case statements).
Is there a way to rewrite it to save it as a view?
Thanks
WITH MNP AS
(SELECT
GoodsReceivedID AS ID,
PORef,
MIN(IncomingDate) AS Manip_Start_Date,
SUM(CASE WHEN ArticleType = 'TEX' THEN UNITS ELSE 0 END) AS TEX_Mnp,
SUM(CASE WHEN ArticleType = 'ACC' THEN UNITS ELSE 0 END) AS ACC_Mnp,
SUM(CASE WHEN ArticleType = 'SHOE' THEN UNITS ELSE 0 END) AS SHOE_Mnp,
SUM(CASE WHEN ArticleType = 'TARA' THEN UNITS ELSE 0 END) AS TARA_Mnp,
SUM(CASE WHEN ArticleType NOT IN ('TEX','ACC','SHOE','TARA') THEN UNITS ELSE 0 END) AS MIX_Mnp,
SUM(UNITS) AS Total_Units
FROM dbo.NT_ManipulationResult
GROUP BY PORef, GoodsReceivedID),
INV AS
(SELECT
GoodsReceivedID,
SUM(CASE WHEN UNITOFSUPPLYID = 1 THEN IN_TOTAL_UNITS END) AS Invoice_Units,
SUM (CASE WHEN UNITOFSUPPLYID = 2 THEN IN_TOTAL_UNITS END) AS Invoice_KG,
SUM (InvoiceNet + InvoiceVAT) AS Invoice_TOT
FROM [dbo].[NT_GoodsReceivedInvoice]
GROUP BY GoodsReceivedID
)
SELECT
GR.ID,
GR.VL_Ref,
GR.DateReceived,
MNP.Manip_Start_Date,
COALESCE(DATEDIFF (Day, DateReceived, MNP.Manip_Start_Date),'') AS DaysToManipulate,
WR.Name AS Warehouse,
GR.ArticleOriginID AS Origin,
SP.Name AS Supplier,
GD.Name AS Grade,
COALESCE(INV.Invoice_TOT,0) AS Invoice_TOT,
COALESCE(INV.Invoice_Units,0) AS Invoice_Units,
COALESCE(INV.Invoice_KG,0) AS Invoice_KG,
COALESCE(MNP.Total_Units,0) AS ManipulatedUnits,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN COALESCE(MNP.Total_Units,0) - COALESCE(INV.Invoice_Units,0) ELSE 0 END AS Manip_Difference,
COALESCE(MNP.TEX_Mnp,0) AS TEX_Mnp,
COALESCE(MNP.ACC_Mnp,0) AS ACC_Mnp,
COALESCE(MNP.SHOE_Mnp,0) AS SHOE_Mnp,
COALESCE(MNP.TARA_Mnp,0) AS TARA_Mnp,
COALESCE(MNP.MIX_Mnp,0) AS MIX_Mnp,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN (COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS TEX_Cost,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN 0.35*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS ACC_Cost,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN 1.2*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS SHOE_Cost,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN 0.45*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS TARA_Cost,
CASE WHEN COALESCE(MNP.Total_Units,0) <> 0 THEN 0.8*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS MIX_Cost
FROM dbo.NT_GoodsReceived AS GR
LEFT OUTER JOIN MNP ON GR.ID = MNP.ID
LEFT OUTER JOIN [dbo].[NT_Warehouse] WR ON GR.WarehouseID = WR.ID
LEFT OUTER JOIN [dbo].[NT_ArticleOrigin] AO ON GR.ArticleOriginID = AO.ID
LEFT OUTER JOIN [dbo].[NT_Supplier] SP ON GR.SupplierID = SP.ID
LEFT OUTER JOIN [dbo].[NT_ArticleGrade] GD ON GR.ArticleGradeID = GD.ID
LEFT OUTER JOIN INV ON GR.ID = INV.GoodsReceivedID
WHERE GR.ID NOT IN (19,20)
I found a solution:
Instead of adding MNP and INV as WITH statements within the query, I created them as separate views which I referenced to within this new query which I could now save as view.
Script ended as follows:
SELECT
GR.ID,
GR.VL_Ref,
GR.DateReceived,
MNP.Manip_Start_Date,
COALESCE (DATEDIFF (Day, GR.DateReceived, MNP.Manip_Start_Date),'') AS DaysToManipulate,
WR.Name AS Warehouse,
GR.ArticleOriginID AS Origin,
SP.Name AS Supplier,
GD.Name AS Grade,
COALESCE(INV.Invoice_TOT,0) AS Invoice_TOT,
COALESCE(INV.Invoice_Units,0) AS Invoice_Units,
COALESCE(INV.Invoice_KG,0) AS Invoice_KG,
COALESCE(MNP.Total_Units,0) AS ManipulatedUnits,
CASE WHEN MNP.Total_Units IS NOT NULL THEN MNP.Total_Units - INV.Invoice_Units ELSE 0 END AS Manip_Difference,
COALESCE(MNP.TEX_Mnp,0) AS TEX_Mnp,
COALESCE(MNP.ACC_Mnp,0) AS ACC_Mnp,
COALESCE(MNP.SHOE_Mnp,0) AS SHOE_Mnp,
COALESCE(MNP.TARA_Mnp,0) AS TARA_Mnp,
COALESCE(MNP.MIX_Mnp,0) AS MIX_Mnp,
CASE WHEN MNP.Total_Units IS NOT NULL THEN (COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS TEX_Cost,
CASE WHEN MNP.Total_Units IS NOT NULL THEN 0.35*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS ACC_Cost,
CASE WHEN MNP.Total_Units IS NOT NULL THEN 1.2*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS SHOE_Cost,
CASE WHEN MNP.Total_Units IS NOT NULL THEN 0.45*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS TARA_Cost,
CASE WHEN MNP.Total_Units IS NOT NULL THEN 0.8*(COALESCE(INV.Invoice_TOT,0) / (COALESCE(MNP.TEX_Mnp,0) + 0.35*COALESCE(MNP.ACC_Mnp,0) + 1.2*COALESCE(MNP.SHOE_Mnp,0) + .45*COALESCE(MNP.TARA_Mnp,0) +.8*COALESCE(MNP.MIX_Mnp,0))) ELSE 0 END AS MIX_Cost
FROM dbo.NT_GoodsReceived AS GR
LEFT OUTER JOIN MNP ON GR.ID = MNP.ID
LEFT OUTER JOIN dbo.NT_Warehouse AS WR ON GR.WarehouseID = WR.ID
LEFT OUTER JOIN dbo.NT_ArticleOrigin AS AO ON GR.ArticleOriginID = AO.ID
LEFT OUTER JOIN dbo.NT_Supplier AS SP ON GR.SupplierID = SP.ID
LEFT OUTER JOIN dbo.NT_ArticleGrade AS GD ON GR.ArticleGradeID = GD.ID
LEFT OUTER JOIN INV ON GR.ID = INV.GoodsReceivedID
WHERE (GR.ID NOT IN (19, 20))

SQL Server 2016 - Stuff/XML Path

I have this basic query, bringing back configuration information. Each MatrixCellID is an individual ticket, and each can have multiple StatisticalGroupCodes and StatisicalGroupDescriptions. Currently each MatrixCellID appears multiple times because of its multiple StatisicalGroupCodes. I would like the Code and Description columns to show all in one column, comma separated.
This is my query:
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
CSG.StatisticalGroupCode,
CSG.StatisticalGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
LEFT JOIN CNF_StatisticalGroup CSG on CSGV.StatisticalGroupId = CSG.StatisticalGroupId
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code
I have tried to use Stuff and XML Path, but cannot get it work correctly with my joins.
Thank you in advance.
You can use this.
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
STUFF(StatGrpCode.StatGroupCodes,1,1,'') StatGroupCodes,
STUFF(StatGrpCodeDesc.StatGroupDescription,1,1,'') StatGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupCode
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCode (StatGroupCodes)
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupDescription
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCodeDesc (StatGroupDescription)
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code

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"