Duplication issue with left join only by adding one column - sql

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"

Related

How to not use WHERE in a CASE statement?

SELECT
c.ClaimId, c.Number, s.ClaimStatusId StatusId, c.ClaimedAmount,
c.Created AS Lodged, c.Updated,
(u.UserName + '' + u.LastName) AS Creditor,
c.JobId, j.CompanyName AS JobName,
outcome.Approved AS ApprovedAmount, outcome.Rejected AS RejectedAmount,
s.NormalizedName AS Status, type.Name AS Type, c.Version, c.RemarksCount
FROM
ClaimView c
INNER JOIN
ClaimType type ON c.TypeId = type.ClaimTypeId
LEFT JOIN
ClaimOutcome outcome ON outcome.ClaimId = c.ClaimId
INNER JOIN
Job j ON c.JobId = j.JobId
INNER JOIN
ApplicationUser u ON u.Id = c.CreatedBy
INNER JOIN
ClaimStatus s ON s.ClaimStatusId = c.StatusId
WHERE
c.CreatedBy = #userId
AND c.StatusId > 1
AND c.IsDeleted = (CASE #isAdmin
WHEN 'False' THEN 0
END)
There's #isAdmin variable and I need to return date with #isAdmin IN (1,0) or to not use WHERE c.IsDeleted at all in case of #isAdmin is True. How I can implement it? That's my current code above.
AND c.isDeleted = CASE WHEN #isAdmin = 'False' THEN 0 ELSE c.isDeleted END
You can use a simple OR to
either check on the fact that #isAdmin is NOT false (alternatively you could/should check against #isAdmin='true')
or c.isDeleted = 0
But you will not need both conditions to be true.
...
WHERE
c.CreatedBy = #userId
AND c.StatusId > 1
AND (#isAdmin != 'False' OR c.IsDeleted = 0 )
This should do. Might be overkill, but I think it's also more technically sound with the NULL handing:
(
AND (
#isAdmin = 'False'
AND c.IsDeleted = 0
)
OR
(#isAdmin <> 'False'
AND c.isDeleted IS NULL
)
)

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

ERROR! - Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause

I'm getting this error: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
I've looked around but I can not find anything to help me in my case.
I am using SQL Server 2012
SELECT DISTINCT
CommodityCode.CommodityCode AS ComCode,
Facility.FacilityAcctNum,
Vessel.VesselType,
Facility.FacilityNm,
Case
When Commodities.ShippedReceivedId = 'R' And Commodities.ForeignDomesticId = 'F' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End AS RecF,
Case
When Commodities.ShippedReceivedId = 'R' And Commodities.ForeignDomesticId = 'D' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End AS RecD,
Case
When Commodities.ShippedReceivedId = 'S' And Commodities.ForeignDomesticId = 'D' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End AS Shipped,
Case
When Commodities.ShippedReceivedId = 'S' And Commodities.ForeignDomesticId = 'F' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End AS ShippedF,
Commodities.Destination,
Commodities.Origin,
Commodities.Specific,
CommodityCode.Descr,
Facility.FacilityID,
TransactionCharge.ArrivalDt,
TransactionCharge.DepartDt,
TransactionCharge.DtDocked,
TransactionCharge.DtSailed
FROM Vessel
INNER JOIN Commodities
INNER JOIN CommodityCode ON Commodities.CommodityCode = CommodityCode.CommodityCode
INNER JOIN TransactionCharge ON Commodities.TransactionID = TransactionCharge.TransactionID ON Vessel.VesselID = TransactionCharge.VesselId
INNER JOIN Facility ON TransactionCharge.FacilityID = Facility.FacilityID
INNER JOIN Unit ON Commodities.Unit = Unit.Unit
INNER JOIN TransactionFee ON TransactionCharge.TransactionID = TransactionFee.TransactionID
GROUP BY
CommodityCode.CommodityCode,
Facility.FacilityAcctNum,
Vessel.VesselType,
Facility.FacilityNm,
Commodities.Destination,
Commodities.Origin,
Commodities.Specific,
CommodityCode.Descr,
Facility.FacilityID,
Case
When Commodities.ShippedReceivedId = 'R' And Commodities.ForeignDomesticId = 'F' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End,
Case
When Commodities.ShippedReceivedId = 'R' And Commodities.ForeignDomesticId = 'D' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End,
Case
When Commodities.ShippedReceivedId = 'S' And Commodities.ForeignDomesticId = 'D' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End,
Case
When Commodities.ShippedReceivedId = 'S' And Commodities.ForeignDomesticId = 'F' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End,
TransactionCharge.ArrivalDt,
TransactionCharge.DepartDt,
TransactionCharge.DtDocked,
TransactionCharge.DtSailed
HAVING (Vessel.VesselType='V' Or Vessel.VesselType='O')
You have subqueries in your case statement in your GROUP BY. For example, looking at the first part of the case statement:
When Commodities.ShippedReceivedId = 'R' And Commodities.ForeignDomesticId = 'F' Then
Case When Commodities.Amount Is Null Or Commodities.Unit Is Null Then Null
Else
Round (Commodities.Amount/Case When Commodities.Unit = 'B' Then (Select BushelFactor From CommodityCode
Where CommodityCode.CommodityCode = Commodities.CommodityCode)
Else (Select ShortTonFactor From Unit
Where Unit.Unit = Commodities.Unit) End,2
)
End
Else 0
End,
There are two there to start with, beginning with Select BushelFactor... and Select ShortTonFactor..., so you will have to remove them.
I had a quick go at reformatting your query and removing/ commenting some of the issues with it:
SELECT --DISTINCT - do you really want DISTINCT?
cc.CommodityCode AS ComCode,
f.FacilityAcctNum,
v.VesselType,
f.FacilityNm,
CASE
WHEN Commodities.ShippedReceivedId = 'R' AND Commodities.ForeignDomesticId = 'F' THEN
CASE
WHEN Commodities.Amount IS NULL OR Commodities.Unit IS NULL THEN NULL
ELSE ROUND(Commodities.Amount /
CASE
WHEN Commodities.Unit = 'B' THEN cc.BushelFactor
ELSE u.ShortTonFactor
END, 2)
END
ELSE 0
END AS RecF,
CASE
WHEN Commodities.ShippedReceivedId = 'R' AND Commodities.ForeignDomesticId = 'D' THEN
CASE
WHEN Commodities.Amount IS NULL OR Commodities.Unit IS NULL THEN NULL
ELSE
ROUND(Commodities.Amount /
CASE
WHEN Commodities.Unit = 'B' THEN cc.BushelFactor
ELSE u.ShortTonFactor END, 2)
END
ELSE 0
END AS RecD,
CASE
WHEN Commodities.ShippedReceivedId = 'S' AND Commodities.ForeignDomesticId = 'D' THEN
CASE
WHEN Commodities.Amount IS NULL OR Commodities.Unit IS NULL THEN NULL
ELSE
ROUND(Commodities.Amount /
CASE
WHEN Commodities.Unit = 'B' THEN cc.BushelFactor
ELSE u.ShortTonFactor
END, 2)
END
ELSE 0
END AS Shipped,
CASE
WHEN Commodities.ShippedReceivedId = 'S' AND Commodities.ForeignDomesticId = 'F' THEN
CASE
WHEN Commodities.Amount IS NULL OR Commodities.Unit IS NULL THEN NULL
ELSE
ROUND(Commodities.Amount/
CASE
WHEN Commodities.Unit = 'B' THEN cc.BushelFactor
ELSE u.ShortTonFactor
END, 2)
END
ELSE 0
END AS ShippedF,
c.Destination,
c.Origin,
c.Specific,
cc.Descr,
f.FacilityID,
tc.ArrivalDt,
tc.DepartDt,
tc.DtDocked,
tc.DtSailed
FROM
Vessel v
INNER JOIN Commodities c ON --some_condtion, OR is this a cross join?
INNER JOIN CommodityCode cc ON c.CommodityCode = cc.CommodityCode
INNER JOIN TransactionCharge tc ON c.TransactionID = tc.TransactionID AND v.VesselID = tc.VesselId
INNER JOIN Facility f ON tc.FacilityID = f.FacilityID
INNER JOIN Unit u ON c.Unit = u.Unit
INNER JOIN TransactionFee td ON tc.TransactionID = tf.TransactionID
WHERE
v.VesselType IN ('V', 'O');
I don't expect this to produce the answers you want, but it might make it easier to spot what is wrong with your original query now that the logic is somewhat simplified?

How to get the max date for multiple conditions

A bit new to Oracle specific SQL syntax, more familiar with MS SQL Server.
I'm having trouble with a join.
Specifically, the join is supposed to allow me to return the most recent date from a table. (In SQL Server I would just put select top 1 date order by date---with oracle it is confusing!)
Here is my entire query, I'm trying to return the max date for each of the date columns in the select statement with the MAX( prefix. (I know the max prefix isn't the correct syntax to get what I'm after, I'm just listing that here so you know which dates I need max date back on..) How do I get the most current date back for those columns?:
SELECT DISTINCT
req.LCR_REQUEST_ID "Request_ID"
,req.MATTER_ID AS "MatterID_lcr"
,req.CUSTOMER_NAME AS "AccountName_lcr"
,req.STATUS AS "CurrentContractStatus_lcr"
,MAX(HIS.RECORDED_DATE) AS "CurrentStatus_ChangeDate"
--,HIS.STATUS AS "ContractStatus_Historic_lcr"
,MAX(HIS_SUB.RECORDED_DATE) AS "Submitted_Status_Date"
--,HIS_NA.RECORDED_DATE AS "NotAssigned_Status_Date"
,MAX(HIS_AtA.RECORDED_DATE) AS "AssignedToAttorney_Status_Date"
,MAX(HIS_SCIN.RECORDED_DATE) AS "InNegotiation_Status_Date"
,MAX(HIS_EXE.RECORDED_DATE) AS "Executed_Status_Date"
,MAX(HIS_CONV.RECORDED_DATE) AS "ConverteToAmend_Status_Date"
,MAX(HIS_DEAD.RECORDED_DATE) AS "Dead_Status_Date"
,MAX(HIS_COMP.RECORDED_DATE) AS "Completed_Status_Date"
,MAX(HIS_EXP.RECORDED_DATE) AS "Expired_Status_Date"
,CASE
WHEN req.DEALSIZE = 0 THEN ''
WHEN req.DEALSIZE = 1 THEN 'Less Than 100K'
when req.DEALSIZE = 2 THEN '100K-500K'
when req.DEALSIZE = 3 THEN '500K-1M'
when req.DEALSIZE = 4 THEN '1M-10M'
when req.DEALSIZE = 5 THEN '>10M'
END
AS "DealSize_lcr"
,cm_out.PTY_NAME AS "AccountName_cm"
,cm_out.PTY_ID AS "PTYID_CM"
,req.customer_id "PtyID_lcr"
,cm_out.EFFECTIVE_DATE "EffDate_lcr"
,cm_out.INITIALTERM_END_DATE "CPEDate_lcr"
,cm_out.CONTRACT_TERMINATION_DATE "FCTDate_lcr"
,cm_out.TERM_NOTICE_NONCOMP_REASON "ReasonForTermination_lcr"
,cm_out.TERM_TYPE "TermType_lcr"
,cm_out.INITIALTERM_DURATION "InitialTerm_lcr"
,cm_out.INVOICE_TIMEMEAS "InitialTermTymeMeas_lcr"
,cm_out.NUMBER_OF_RENEWALS "NumberOfRenewals_lcr"
,req.AMENDMENT "ParentMatterID_lcr"
,prod.rpg "RPG_lcr"
,prod.SALES_PRODUCT_NAME "Product_lcr"
,prod.CONTRACT_TYPE "ContractType_lcr"
,req.CONTRACT_ROLE "ContractRole_lcr"
,cm_out.METADATA_FLAG "MetaFlag_lcr"
,CASE
WHEN cm_out.DATA_AUTO_IMPORT_YN = 1 THEN 'YES'
WHEN cm_out.REQUESTOR = 'Imported Record' THEN 'YES'
ELSE 'NO'
END
"DataImport_lcr"
,CASE act.actionstatus
WHEN 'Cancel Date Update' THEN 'Yes'
ELSE NULL
END "ActionToCancelAutoDate_lcr"
,req_emp.FIRST_NAME || ' ' || req_emp.LAST_NAME "Requestor_lcr"
,att_emp.FIRST_NAME || ' ' || att_emp.LAST_NAME "Attorney_lcr"
,req.REQUESTOR_DEPARTMENT "Requestor_Department_lcr"
,req.AGREEMENT_TITLE "AgreementTitle_lcr"
,req.DATE_RECORDED
FROM LCR_REQUEST REQ
LEFT JOIN LCR_ACTION ACT ON req.MATTER_ID = act.MATTER_ID
LEFT JOIN CM_CONTRACT_OUTBOUND cm_out ON cm_out.MATTER_ID = NVL(req.MATTER_ID,req.AMENDMENT)
LEFT JOIN LCR_REQUEST_PRODUCT prod_REQ ON prod_req.LCR_REQUEST_ID = req.LCR_REQUEST_ID
LEFT JOIN LCR_PRODUCT PROD ON prod.PRODUCT_ID = prod_req.PRODUCT_ID
LEFT JOIN LCR_EMPLOYEE att_emp ON req.ASSIGNED_TO = att_emp.ORACLE_PERSON_ID
LEFT JOIN LCR_EMPLOYEE req_emp ON req.REQUESTED_BY_ID = req_emp .ORACLE_PERSON_ID
LEFT JOIN LCR_STATUS_HISTORY HIS ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID AND ((HIS.STATUS = REQ.STATUS) OR (HIS.STATUS = 'Assigned to Attorney' AND REQ.STATUS = 'Assigned To Attorney'))
--LEFT JOIN LCR_STATUS_HISTORY HIS_NA ON req.LCR_REQUEST_ID = HIS_NA.LCR_REQUEST_ID AND HIS_NA.STATUS = 'Not Assigned'
LEFT JOIN LCR_STATUS_HISTORY HIS_AtA ON req.LCR_REQUEST_ID = HIS_AtA.LCR_REQUEST_ID AND HIS_AtA.STATUS = 'Assigned to Attorney'
LEFT JOIN LCR_STATUS_HISTORY HIS_SUB ON req.LCR_REQUEST_ID = HIS_SUB.LCR_REQUEST_ID AND HIS_SUB.STATUS = 'Submitted'
LEFT JOIN LCR_STATUS_HISTORY HIS_SCIN ON req.LCR_REQUEST_ID = HIS_SCIN.LCR_REQUEST_ID AND HIS_SCIN.STATUS = 'Submission Complete-In Negotiation'
LEFT JOIN LCR_STATUS_HISTORY HIS_EXE ON req.LCR_REQUEST_ID = HIS_EXE.LCR_REQUEST_ID AND HIS_EXE.STATUS = 'Executed'
LEFT JOIN LCR_STATUS_HISTORY HIS_CONV ON req.LCR_REQUEST_ID = HIS_CONV.LCR_REQUEST_ID AND HIS_CONV.STATUS = 'Converted to amendment.'
LEFT JOIN LCR_STATUS_HISTORY HIS_DEAD ON req.LCR_REQUEST_ID = HIS_DEAD.LCR_REQUEST_ID AND HIS_DEAD.STATUS = 'Dead'
LEFT JOIN LCR_STATUS_HISTORY HIS_COMP ON req.LCR_REQUEST_ID = HIS_COMP.LCR_REQUEST_ID AND HIS_COMP.STATUS = 'Completed'
LEFT JOIN LCR_STATUS_HISTORY HIS_EXP ON req.LCR_REQUEST_ID = HIS_EXP.LCR_REQUEST_ID AND HIS_EXP.STATUS = 'Expired/Terminated'
WHERE REQ.CATEGORY_NAME = 'Sales'
AND
REQ.DATE_RECORDED BETWEEN to_date ('07/01/2012', 'mm/dd/yyyy') AND to_date ('06/30/2013','mm/dd/yyyy')
GROUP BY
req.LCR_REQUEST_ID
,req.MATTER_ID
,req.CUSTOMER_NAME
,req.STATUS
,HIS.RECORDED_DATE
--,HIS.STATUS
,HIS_SUB.RECORDED_DATE
--,HIS_NA.RECORDED_DATE
,HIS_AtA.RECORDED_DATE
,HIS_SCIN.RECORDED_DATE
,HIS_EXE.RECORDED_DATE
,HIS_CONV.RECORDED_DATE
,HIS_DEAD.RECORDED_DATE
,HIS_COMP.RECORDED_DATE
,HIS_EXP.RECORDED_DATE
,CASE
WHEN req.DEALSIZE = 0 THEN ''
WHEN req.DEALSIZE = 1 THEN 'Less Than 100K'
when req.DEALSIZE = 2 THEN '100K-500K'
when req.DEALSIZE = 3 THEN '500K-1M'
when req.DEALSIZE = 4 THEN '1M-10M'
when req.DEALSIZE = 5 THEN '>10M'
END
,cm_out.PTY_NAME
,cm_out.PTY_ID
,req.customer_id
,cm_out.EFFECTIVE_DATE
,cm_out.INITIALTERM_END_DATE
,cm_out.CONTRACT_TERMINATION_DATE
,cm_out.TERM_NOTICE_NONCOMP_REASON
,cm_out.TERM_TYPE
,cm_out.INITIALTERM_DURATION
,cm_out.INVOICE_TIMEMEAS
,cm_out.NUMBER_OF_RENEWALS
,req.AMENDMENT
,prod.rpg
,prod.SALES_PRODUCT_NAME
,prod.CONTRACT_TYPE
,req.CONTRACT_ROLE
,cm_out.METADATA_FLAG
,CASE
WHEN cm_out.DATA_AUTO_IMPORT_YN = 1 THEN 'YES'
WHEN cm_out.REQUESTOR = 'Imported Record' THEN 'YES'
ELSE 'NO'
END
,CASE act.actionstatus
WHEN 'Cancel Date Update' THEN 'Yes'
ELSE NULL
END
,req_emp.FIRST_NAME || ' ' || req_emp.LAST_NAME
,att_emp.FIRST_NAME || ' ' || att_emp.LAST_NAME
,req.REQUESTOR_DEPARTMENT
,req.AGREEMENT_TITLE
,req.DATE_RECORDED;
I wonder how you get multiple columns with a max date using a single TOP 1?
Most of the LEFT JOINs to LCR_STATUS_HISTORY can easily be replaced by a single join using MAX(CASE):
LEFT JOIN
(
SELECT LCR_REQUEST_ID,
MAX(CASE WHEN STATUS = 'Assigned to Attorney' THEN RECORDED_DATE END) AS "AssignedToAttorney_Status_Date"
,MAX(CASE WHEN STATUS = 'Submission Complete-In Negotiation' THEN RECORDED_DATE END) AS "InNegotiation_Status_Date"
,...
FROM LCR_STATUS_HISTORY
GROUP BY LCR_REQUEST_ID
) his
ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID
Then you probably don't need the GROUP BY any more.
And in this join-condition the OR-part can be removed:
((HIS.STATUS = REQ.STATUS) OR (HIS.STATUS = 'Assigned to Attorney' AND REQ.STATUS = 'Assigned To Attorney'))
ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID

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