Left outer join invalid identifier - sql

I can't seem to get these left outer joins right using derived tables. I need to do it this way as I need to use a subquery in the qualification.
The error I am receiving is ORA-00904: "E"."ENCNTR_ID": invalid identifier
I've tried moving the position of the join around and reversing the columns around the =. There's plenty of posts out there related to this but none of them have provided me the answer. Many are in regards to having multiple tables comma delimited in the FROM clause but my query doesn't have that.
SELECT
E.ENCNTR_ID
,E.REASON_FOR_VISIT
-- ,D.DIAGNOSIS_DISPLAY AS DISCHARGE_DX
-- ,D.DIAG_FTDESC AS WORKING_DX
,cclsql_cnvtdatetimeutc(E.REG_DT_TM, 2, 126) as reg_dt_tm
,cclsql_cnvtdatetimeutc(E.DISCH_DT_TM, 2, 126) as disch_dt_tm
,FACILITY.DISPLAY AS FACILITY
,P.PERSON_ID
,P.NAME_FULL_FORMATTED
,cclsql_cnvtdatetimeutc(P.BIRTH_DT_TM, 2, P.BIRTH_TZ) as birth_dt_tm
,MRN.ALIAS AS MRN
,FIN.ALIAS AS FIN
,ENC_TYPE.DISPLAY AS ENCOUNTER_TYPE
,NURSE_UNIT.DISPLAY AS NURSE_UNIT
,ROOM.DISPLAY AS ROOM
,BED.DISPLAY AS BED
,ADMITDOC_NAME.NAME_FULL_FORMATTED AS ADMITDOC_NAME
,DCDOC_NAME.NAME_FULL_FORMATTED AS DCDOC_NAME
,ADMIT_SRC.DISPLAY AS ADMIT_SOURCE
,ADMIT_TYPE.DISPLAY AS ADMIT_TYPE
,ESDP.RESULT_VAL AS ESDP
,DISCH_DISPOSITION.DISPLAY AS DISCH_DISPOSITION
FROM ENCOUNTER E
-- JOIN DISCHARGE D ON (D.ENCNTR_ID = E.ENCNTR_ID)
-- AND D.ACTIVE_IND = 1
-- AND D.END_EFFECTIVE_DT_TM > SYSDATE
JOIN PERSON P ON (P.PERSON_ID = E.PERSON_ID)
JOIN CODE_VALUE ENC_TYPE ON (ENC_TYPE.CODE_VALUE = E.ENCNTR_TYPE_CLASS_CD)
JOIN ENCNTR_ALIAS FIN ON (FIN.ENCNTR_ID = E.ENCNTR_ID)
AND FIN.ENCNTR_ALIAS_TYPE_CD = 1077 -- FIN CODE
AND FIN.ACTIVE_IND = 1
AND FIN.ACTIVE_STATUS_CD = 188
JOIN ENCNTR_ALIAS MRN ON (MRN.ENCNTR_ID = E.ENCNTR_ID)
AND MRN.ENCNTR_ALIAS_TYPE_CD = 1079 -- MRN CODE
AND MRN.ACTIVE_IND = 1
AND MRN.ACTIVE_STATUS_CD = 188
JOIN CODE_VALUE FACILITY on (FACILITY.CODE_VALUE = E.LOC_FACILITY_CD)
JOIN CODE_VALUE NURSE_UNIT on (NURSE_UNIT.CODE_VALUE = E.LOC_NURSE_UNIT_CD)
JOIN CODE_VALUE ROOM on (ROOM.CODE_VALUE = E.LOC_ROOM_CD)
JOIN CODE_VALUE BED on (BED.CODE_VALUE = E.LOC_BED_CD)
JOIN CODE_VALUE DISCH_DISPOSITION on (DISCH_DISPOSITION.CODE_VALUE = E.DISCH_DISPOSITION_CD)
JOIN PRSNL ADMITDOC_NAME ON (ADMITDOC_NAME.PERSON_ID = OA.ORDER_PROVIDER_ID)
LEFT JOIN CLINICAL_EVENT HOSP_SUM ON (HOSP_SUM.ENCNTR_ID = E.ENCNTR_ID)
AND HOSP_SUM.EVENT_CD = :p17
AND HOSP_SUM.RESULT_STATUS_CD IN (:p19, :p20, :p21)
AND HOSP_SUM.RECORD_STATUS_CD = 188 -- ACTIVE
AND HOSP_SUM.VALID_UNTIL_DT_TM > cclsql_cnvtdatetimeutc(SYSDATE, 1, 126)
LEFT JOIN PRSNL DCDOC_NAME ON (DCDOC_NAME.PERSON_ID = HOSP_SUM.VERIFIED_PRSNL_ID)
JOIN CODE_VALUE ADMIT_SRC ON (ADMIT_SRC.CODE_VALUE = E.ADMIT_SRC_CD)
JOIN CODE_VALUE ADMIT_TYPE ON (ADMIT_TYPE.CODE_VALUE = E.ADMIT_TYPE_CD)
LEFT JOIN CLINICAL_EVENT ESDP ON (ESDP.ENCNTR_ID = E.ENCNTR_ID)
AND ESDP.EVENT_CD = :p18
AND ESDP.RESULT_STATUS_CD IN (:p19, :p20, :p21)
AND ESDP.RECORD_STATUS_CD = 188 -- ACTIVE
AND ESDP.VALID_UNTIL_DT_TM > cclsql_cnvtdatetimeutc(SYSDATE, 1, 126)
LEFT JOIN (
SELECT O.* FROM ORDERS O WHERE O.ORDER_ID = (
SELECT MAX(O2.ORDER_ID) FROM ORDERS O2 WHERE O2.ENCNTR_ID = E.ENCNTR_ID AND O2.CATALOG_CD = :p22 AND O2.ACTIVE_IND = 1
)) O ON
O.ENCNTR_ID = E.ENCNTR_ID
-- LEFT OUTER JOIN (
-- SELECT * FROM ORDER_ACTION WHERE ORDER_ID = O.ORDER_ID AND ACTION_TYPE_CD IN (:p23, :p24) AND ACTION_SEQUENCE = (
-- SELECT MAX(OA2.ACTION_SEQUENCE)
-- FROM ORDER_ACTION OA2
-- WHERE OA2.ORDER_ID = O.ORDER_ID AND OA2.ACTION_TYPE_CD IN (:p23, :p24)
-- )) OA ON
-- O.ORDER_ID = OA.ORDER_ID
WHERE E.ENCNTR_ID IN (:p0, :p1, :p2, :p3, :p4, :p5, :p6, :p7, :p8, :p9, :p10, :p11, :p12, :p13, :p14, :p15, :p16)
ORDER BY PERSON_ID ASC, REG_DT_TM DESC;

E.ENCNTR_ID on the third line below will not be found, because this subquery is outside the scope of the parent query, so you'll need to join your E table in this subquery. However, since you need the ENCTR_ID specificity in this subquery, you should consider using a CTE (WITH Clause) to prefetch this table.
LEFT JOIN (
SELECT O.* FROM ORDERS O WHERE O.ORDER_ID = (
SELECT MAX(O2.ORDER_ID) FROM ORDERS O2 WHERE O2.ENCNTR_ID = E.ENCNTR_ID AND
O2.CATALOG_CD = :p22 AND O2.ACTIVE_IND = 1
)) O ON
O.ENCNTR_ID = E.ENCNTR_ID

It seems the main thing I was lacking was using a GROUP BY in my subquery. I didn't need to use a derived table at all. Just use a subquery with GROUP BY and duplicate the qualifications in the main join query and the subquery.
SELECT
E.ENCNTR_ID
,E.REASON_FOR_VISIT
-- ,D.DIAGNOSIS_DISPLAY AS DISCHARGE_DX
-- ,D.DIAG_FTDESC AS WORKING_DX
,cclsql_cnvtdatetimeutc(E.REG_DT_TM, 2, 126) as reg_dt_tm
,cclsql_cnvtdatetimeutc(E.DISCH_DT_TM, 2, 126) as disch_dt_tm
,FACILITY.DISPLAY AS FACILITY
,P.PERSON_ID
,P.NAME_FULL_FORMATTED
,cclsql_cnvtdatetimeutc(P.BIRTH_DT_TM, 2, P.BIRTH_TZ) as birth_dt_tm
,MRN.ALIAS AS MRN
,FIN.ALIAS AS FIN
,ENC_TYPE.DISPLAY AS ENCOUNTER_TYPE
,NURSE_UNIT.DISPLAY AS NURSE_UNIT
,ROOM.DISPLAY AS ROOM
,BED.DISPLAY AS BED
-- ,ADMITDOC_NAME.NAME_FULL_FORMATTED AS ADMITDOC_NAME
,DCDOC_NAME.NAME_FULL_FORMATTED AS DCDOC_NAME
,ADMIT_SRC.DISPLAY AS ADMIT_SOURCE
,ADMIT_TYPE.DISPLAY AS ADMIT_TYPE
,ESDP.RESULT_VAL AS ESDP
,DISCH_DISPOSITION.DISPLAY AS DISCH_DISPOSITION
FROM ENCOUNTER E
-- JOIN DISCHARGE D ON (D.ENCNTR_ID = E.ENCNTR_ID)
-- AND D.ACTIVE_IND = 1
-- AND D.END_EFFECTIVE_DT_TM > SYSDATE
JOIN PERSON P ON (P.PERSON_ID = E.PERSON_ID)
JOIN CODE_VALUE ENC_TYPE ON (ENC_TYPE.CODE_VALUE = E.ENCNTR_TYPE_CLASS_CD)
JOIN ENCNTR_ALIAS FIN ON (FIN.ENCNTR_ID = E.ENCNTR_ID)
AND FIN.ENCNTR_ALIAS_TYPE_CD = 1077 -- FIN CODE
AND FIN.ACTIVE_IND = 1
AND FIN.ACTIVE_STATUS_CD = 188
JOIN ENCNTR_ALIAS MRN ON (MRN.ENCNTR_ID = E.ENCNTR_ID)
AND MRN.ENCNTR_ALIAS_TYPE_CD = 1079 -- MRN CODE
AND MRN.ACTIVE_IND = 1
AND MRN.ACTIVE_STATUS_CD = 188
JOIN CODE_VALUE FACILITY on (FACILITY.CODE_VALUE = E.LOC_FACILITY_CD)
JOIN CODE_VALUE NURSE_UNIT on (NURSE_UNIT.CODE_VALUE = E.LOC_NURSE_UNIT_CD)
JOIN CODE_VALUE ROOM on (ROOM.CODE_VALUE = E.LOC_ROOM_CD)
JOIN CODE_VALUE BED on (BED.CODE_VALUE = E.LOC_BED_CD)
JOIN CODE_VALUE DISCH_DISPOSITION on (DISCH_DISPOSITION.CODE_VALUE = E.DISCH_DISPOSITION_CD)
LEFT JOIN ORDERS O ON
O.ENCNTR_ID = E.ENCNTR_ID AND O.CATALOG_CD = :p22 AND O.ACTIVE_IND = 1 AND O.ORDER_ID IN (
SELECT MAX(O2.ORDER_ID) FROM ORDERS O2 WHERE O2.ENCNTR_ID = E.ENCNTR_ID AND O2.CATALOG_CD = :p22 AND O2.ACTIVE_IND = 1 GROUP BY O2.ENCNTR_ID
)
LEFT JOIN ORDER_ACTION OA ON
OA.ORDER_ID = O.ORDER_ID AND OA.ACTION_TYPE_CD IN (:p23, :p24) AND OA.ACTION_SEQUENCE IN (
SELECT MAX(OA2.ACTION_SEQUENCE) FROM ORDER_ACTION OA2 WHERE OA2.ORDER_ID = O.ORDER_ID AND OA2.ACTION_TYPE_CD IN (:p23, :p24) GROUP BY OA2.ORDER_ID
)
LEFT JOIN PRSNL ADMITDOC_NAME ON (ADMITDOC_NAME.PERSON_ID = OA.ORDER_PROVIDER_ID)
LEFT JOIN CLINICAL_EVENT HOSP_SUM ON (HOSP_SUM.ENCNTR_ID = E.ENCNTR_ID)
AND HOSP_SUM.EVENT_CD = :p17
AND HOSP_SUM.RESULT_STATUS_CD IN (:p19, :p20, :p21)
AND HOSP_SUM.RECORD_STATUS_CD = 188 -- ACTIVE
AND HOSP_SUM.VALID_UNTIL_DT_TM > cclsql_cnvtdatetimeutc(SYSDATE, 1, 126)
LEFT JOIN PRSNL DCDOC_NAME ON (DCDOC_NAME.PERSON_ID = HOSP_SUM.VERIFIED_PRSNL_ID)
JOIN CODE_VALUE ADMIT_SRC ON (ADMIT_SRC.CODE_VALUE = E.ADMIT_SRC_CD)
JOIN CODE_VALUE ADMIT_TYPE ON (ADMIT_TYPE.CODE_VALUE = E.ADMIT_TYPE_CD)
LEFT JOIN CLINICAL_EVENT ESDP ON (ESDP.ENCNTR_ID = E.ENCNTR_ID)
AND ESDP.EVENT_CD = :p18
AND ESDP.RESULT_STATUS_CD IN (:p19, :p20, :p21)
AND ESDP.RECORD_STATUS_CD = 188 -- ACTIVE
AND ESDP.VALID_UNTIL_DT_TM > cclsql_cnvtdatetimeutc(SYSDATE, 1, 126)
WHERE E.ENCNTR_ID IN (:p0, :p1, :p2, :p3, :p4, :p5, :p6, :p7, :p8, :p9, :p10, :p11, :p12, :p13, :p14, :p15, :p16)
ORDER BY PERSON_ID ASC, REG_DT_TM DESC

Related

I get ORA-00905: missing keyword

I write this query and when I run it I get
ORA-00905: missing keyword
I check with many online SQL query checker and all of them answered it is correct can any body help me what's the problem
select *
from T_TimelineItem ti
where ti.C_HIDE = 0
and ti.F_RELATED_BUSINESS = 4335
and exists(select *
from T_Business b
inner join MM_BIZ_GUILDS g on b.C_ID = g.ID1
where b.C_ID = ti.F_RELATED_BUSINESS
and g.ID2 in (49))
and (CASE ti.C_TYPE
WHEN 1 then ti.C_ID in (select po.C_TIMELINEID
from T_PRODUCT pr
inner join T_POST po on po.C_ID = pr.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and pr.F_GUILD in (49))
WHEN 8 THEN ti.C_ID in (select po.C_TIMELINEID
from T_COMPETITION com
inner join T_POST po on po.C_ID = com.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and com.F_GUILD in (49)) END);
Don't use case in where clauses
and (ti.C_TYPE = 1 and ti.C_ID in (select po.C_TIMELINEID
from T_PRODUCT pr
inner join T_POST po on po.C_ID = pr.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and pr.F_GUILD in (49)))
or (ti.C_TYPE = 8 and ti.C_ID in (select po.C_TIMELINEID
from T_COMPETITION com
inner join T_POST po on po.C_ID = com.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and com.F_GUILD in (49)) END))
I have removed multiple in cause you can use equal easily for single value comparison and you don't need to select all the column inside exists
select *
from T_TimelineItem ti
where ti.C_HIDE = 0
and ti.F_RELATED_BUSINESS = 4335
and exists(select 1
from T_Business b
inner join MM_BIZ_GUILDS g on b.C_ID = g.ID1
where b.C_ID = ti.F_RELATED_BUSINESS
and g.ID2 = 49
)
and (ti.C_TYPE=1
and ti.C_ID in (select po.C_TIMELINEID
from T_PRODUCT pr
inner join T_POST po
on po.C_ID = pr.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and pr.F_GUILD =49
)
or ( ti.C_TYPE=8 and
ti.C_ID in (select po.C_TIMELINEID
from T_COMPETITION com
inner join T_POST po on po.C_ID = com.F_POST
where po.F_BUSINESS = ti.F_RELATED_BUSINESS
and com.F_GUILD =49
)

SQL Filtering rows with no duplicate value

Hi so I'm new to SQL and I'm trying to find a way in which I can obtain only the rows that have values that are not duplicate to each other in a specific column of table.
For example the Table below is called T1 and contains:
ID|Branch ID
1 444
2 333
3 444
4 111
5 555
6 333
The result I want will be
ID|Branch ID
4 111
5 555
So only showing non duplicate rows
Edit: I want to apply this to a large relational code. Here is a snippet of where I want it to be added
FROM dbo.LogicalLine
INNER JOIN dbo.Page ON dbo.LogicalLine.page_id = dbo.Page.id
INNER JOIN dbo.Branch ON dbo.LogicalLine.branch_id = dbo.Branch.id
The table LogicalLine will have a column called branch_id containing duplicate id values. I wish to filter those out showing only the non-duplicate branch_id like above example then INNER JOIN the Branch table into the LogicalLine which I have done.
Added -Full Code here:
SELECT
(SELECT name
FROM ParentDevice
WHERE (Dev1.type NOT LIKE '%cable%') AND (id = Dev1.parent_device_id))T1_DeviceID,
(SELECT name
FROM Symbol
WHERE (id = CP1.symbol_id) AND (type NOT LIKE '%cable%'))T1_DeviceName,
(SELECT name
FROM Location
WHERE (id = Page.location_id))T1_Location,
(SELECT name
FROM Installation
WHERE (id = Page.installation_id))T1_Installation,
(SELECT name
FROM ParentDevice
WHERE (Dev2.type NOT LIKE '%cable%') AND (id = Dev2.parent_device_id))T2_DeviceID,
(SELECT name
FROM Symbol
WHERE ( id = CP2.symbol_id) AND (type NOT LIKE '%cable%'))T2_DeviceName,
(SELECT name
FROM Location
WHERE (id = PD2.location_id))T2_Location,
(SELECT name
FROM Installation
WHERE (id = Page.installation_id))T2_Installation,
(SELECT devicefamily
FROM Device
WHERE (type LIKE '%cable%') AND (id = SymCable.device_id))CablePartNumber,
(SELECT name
FROM ParentDevice
WHERE (id = DevCable.parent_device_id) AND (DevCable.type LIKE '%cable%'))CableTag
FROM dbo.LogicalLine
INNER JOIN dbo.Page ON dbo.LogicalLine.page_id = dbo.Page.id
INNER JOIN dbo.Branch ON dbo.LogicalLine.branch_id = dbo.Branch.id
LEFT OUTER JOIN dbo.Symbol AS SymCable ON dbo.LogicalLine.cable_id = SymCable.id
LEFT OUTER JOIN dbo.Device AS DevCable ON SymCable.device_id = DevCable.id
LEFT OUTER JOIN dbo.ParentDevice AS ParentCable ON DevCable.parent_device_id = ParentCable.id
INNER JOIN dbo.SymbolCP AS CP1 ON dbo.Branch.cp1_id = CP1.id
INNER JOIN dbo.SymbolCP AS CP2 ON dbo.Branch.cp2_id = CP2.id
INNER JOIN dbo.Symbol AS S1 ON CP1.symbol_id = S1.id
INNER JOIN dbo.Symbol AS S2 ON CP2.symbol_id = S2.id
INNER JOIN dbo.Device AS Dev1 ON S1.device_id = Dev1.id
INNER JOIN dbo.Device AS Dev2 ON S2.device_id = Dev2.id
INNER JOIN dbo.ParentDevice AS PD1 ON Dev1.parent_device_id = PD1.id
INNER JOIN dbo.ParentDevice AS PD2 ON Dev2.parent_device_id = PD2.id
INNER JOIN dbo.Location AS L1 ON PD1.location_id = L1.id
INNER JOIN dbo.Location AS L2 ON PD2.location_id = L2.id
INNER JOIN dbo.Installation AS I1 ON L1.installation_id = I1.id
INNER JOIN dbo.Installation AS I2 ON L2.installation_id = I2.id
WHERE
(PD1.project_id = #Projectid) AND (dbo.LogicalLine.drawingmode LIKE '%Single Line%');
Select Id, BranchId from table t
Where not exists
(Select * from table
where id != t.Id
and BranchId = t.BranchId)
or
Select Id, BranchId
From table
Group By BranchId
Having count(*) == 1
EDIT: to modify as requested, simply add to your complete SQL query a Where clause:
Select l.Id BranchId, [plus whatever else you have in your select clause]
FROM LogicalLine l
join Page p ON p.id = l.page_Id
join Branch b ON b.Id = l.branch_id
Group By l.branch_id, [Plus whatever else you have in Select clause]
Having count(*) == 1
or
Select l.Id BranchId, [plus whatever else you have in your select clause]
FROM LogicalLine l
join Page p on p.id = l.page_Id
join Branch b on b.Id = l.branch_id
Where not exists
(Select * from LogicalLine
where id != l.Id
and branch_id = l.branch_id)

using a subquery as a column that's using another column in the 'where' clause

I probably messed that title up! So I have a column called "programID" and I want another column to tell me the most recent date an order was placed using the programID. I think I'd need a subcolumn but the problem is how do I use the row's programID so that it matches the programID for the same row?
DECLARE #ClientIDs varchar(4) = 6653;
DECLARE #ProgramStatus char(1) = 'Y'; -- Y, N, or R
SELECT
rcp.RCPID AS ProgramID
, rcp.RCPName AS Program
, rcp.RCPActive AS ProgramStatus
, aa.AACustomCardInternalReview AS VCCP
, aa.AAJobNo AS AAJobNo
, aas.AASName AS AAStatus
, rcp.RCPOpsApproved AS OpsApproved
, clt.CltID AS ClientID
, rcp.RCPSignatureRequired AS SignatureRequired
, st.STEnumValue AS DefaultShipType
, rcp.RCPShipMethodOverrideType AS ShipTypeOverride
,aa.AANetworkProgramID
,(Select max(cdconfirmationdate) from carddet where ) --can't figure this part out
FROM
RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN ClientRetailerMap crm WITH (NOLOCK)
ON crm.CRMRetailerID = rcp.RCPRetailerID
INNER JOIN Client clt WITH(NOLOCK)
ON clt.CltID = crm.CRMCltID
LEFT JOIN AssociationApproval aa WITH (NOLOCK)
ON aa.AARetailerID = rcp.RCPRetailerID
AND aa.AABin = rcp.RCPBin6
AND aa.AAFrontOfPlasticTemplateID = rcp.RCPFOCTemplateID
AND aa.AABackOfPlasticTemplateID = rcp.RCPBOCTemplateID
AND ISNULL(aa.AACardID, 0) = ISNULL(rcp.RCPDefaultPlasticCardID, 0)
-- AND LOWER(rcp.RCPName) NOT LIKE '%do not use%' -- Needed for AA Job Number 1594
LEFT JOIN AssociationApprovalStatus aas WITH (NOLOCK)
ON aas.AASID = aa.AAAssociationApprovalStatusID
LEFT JOIN OpenLoopAssociation ola WITH (NOLOCK)
ON ola.OLAID=rcp.RCPOLAID
LEFT JOIN ClientCardProgramMap ccpm WITH (NOLOCK)
ON ccpm.CCPMCardProgramID = rcp.RCPID
AND ccpm.CCPMClientID = clt.CltID
LEFT JOIN TippingModule tm WITH (NOLOCK)
ON tm.TMid = rcp.RCPTippingModuleID
LEFT JOIN GiftCardTemplate fgt WITH (NOLOCK)
ON fgt.gtid = rcp.RCPFOCTemplateID
AND fgt.GTPage='P'
LEFT JOIN GiftCardTemplate bgt WITH (NOLOCK)
ON bgt.gtid = rcp.RCPBOCTemplateID
AND bgt.GTPage='PB'
LEFT JOIN Card c WITH (NOLOCK)
ON c.CardID = rcp.RCPDefaultCarrierID
LEFT JOIN CardType ct WITH (NOLOCK)
ON ct.CTID = c.CardTypeID
LEFT JOIN RetailerCardProgramTCSheetMap rtm1 WITH (NOLOCK)
ON rtm1.RTMRCPID = rcp.RCPID
AND rtm1.RTMInsertOrder = 1
LEFT JOIN RetailerCardProgramTCSheetMap rtm2 WITH (NOLOCK)
ON rtm2.RTMRCPID = rcp.RCPID
AND rtm2.RTMInsertOrder = 2
LEFT JOIN RetailerCardProgramTCSheetMap rtm3 WITH (NOLOCK)
ON rtm3.RTMRCPID = rcp.RCPID
AND rtm3.RTMInsertOrder = 3
LEFT JOIN RetailerCardProgramTCSheetMap rtm4 WITH (NOLOCK)
ON rtm4.RTMRCPID = rcp.RCPID
AND rtm4.RTMInsertOrder = 4
LEFT JOIN TCSheet i1 WITH (NOLOCK)
ON i1.TCSID = rtm1.RTMTCSID
LEFT JOIN TCSheet i2 WITH (NOLOCK)
ON i2.TCSID = rtm2.RTMTCSID
LEFT JOIN TCSheet i3 WITH (NOLOCK)
ON i3.TCSID = rtm3.RTMTCSID
LEFT JOIN TCSheet i4 WITH (NOLOCK)
ON i4.TCSID = rtm4.RTMTCSID
LEFT JOIN ShipType st WITH (NOLOCK)
ON st.STId = rcp.RCPDefaultShipTypeID
WHERE
clt.CltID IN (#ClientIDs) -- 6653 and 6657.
AND rcp.RCPActive IN (#ProgramStatus)
ORDER BY
AAJobNo
, Program
You want to join with a nested select on the table carddet. I'm inferring that RCPID is the relationship between carddet and your main table RetainerCardProgram...
SELECT rcp.RCPID AS ProgramID,
date.MAXDATE AS MaxDate,
rest of your columns...
FROM RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN (
SELECT RCPID, MAX(cdconfirmationdate) as 'MAXDATE'
FROM carddet
GROUP BY RCPID
) date on date.RCPID = rcp.RCPID
rest of query...
You may want a left join if not all IDs have a date in carddet.
Obligatory addition: Also your use of NOLOCK is a bit terrifying. See http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/

Why query with MAX(Date) dosen't return any record?

I have a sql query like below:
SELECT CPH.CheckPointID,
CPH.ID AS Check_Point_History_ID,
CLCP.SequenceNo AS Sequence,
CP.Code AS Point_Code,
CPV.ID,
TT.Medium AS Description,
[TEXT_TRANSLATION_ANS].[Medium] AS Value,
CPH.Value_ AS Additional_Information,
EMP.NAME AS Checked_By,
CPH.AnsweredOn AS Checked_On
FROM CHECK_LIST_HISTORY CLH
LEFT JOIN CHECK_POINT_HISTORY CPH
ON CLH.ID = CPH.CheckListHistoryID
INNER JOIN (
SELECT CPH2.CheckPointID,
MAX(CPH2.AnsweredOn) AS MaxDate
FROM CHECK_LIST_HISTORY CLH2
LEFT JOIN CHECK_POINT_HISTORY CPH2
ON CLH2.ID = CPH2.CheckListHistoryID
GROUP BY CPH2.CheckPointID
) tm
ON CPH.CheckPointID = tm.CheckPointID
AND CPH.AnsweredOn = tm.MaxDate
LEFT JOIN CHECK_POINT CP
ON CPH.CheckPointID = CP.ID
LEFT JOIN CHECK_POINT_VALUE CPV
ON CPH.CheckPointValueID = CPV.ID
LEFT JOIN TEXT_TRANSLATION TT
ON CP.TextID = TT.TextID
AND TT.LanguageID = LanguageID
LEFT JOIN CHECK_LIST_CHECK_POINT CLCP
ON CP.ID = CLCP.CheckPointID
LEFT JOIN EMPLOYEE EMP
ON CPH.EmployeeID = EMP.ID
LEFT JOIN [TEXT_TRANSLATION] [TEXT_TRANSLATION_ANS]
ON CPV.AnswerTextID = [TEXT_TRANSLATION_ANS].[TextID]
AND [TEXT_TRANSLATION_ANS].[LanguageID] = TT.LanguageID
LEFT JOIN [TEXT_TRANSLATION] [TEXT_TRANSLATION_RES]
ON CPV.ResponseTextID = [TEXT_TRANSLATION_RES].[TextID]
AND [TEXT_TRANSLATION_RES].[LanguageID] = TT.LanguageID
WHERE CLH.WipOrderNo = 304
AND CLH.WipOrderType = 26
AND CLCP.WorkCenter = 'WC03'
AND CLCP.Facility = 'C1P1'
This query should return me two records with maximum date, but it returns nothing. I think the problem is in the INNER JOIN because when the line with the INNER JOIN is commented, the query returns the following table:

Join two select queries horizontally in Postgresql

I have following two queries:
Query #1:
(SELECT
pl.c_project_Id, pl.c_projectphase_Id, pl.c_projecttask_Id, pl.m_product_Id,
pj.name as projectname, ph.name as phasename, pt.name as taskname, pd.name as prodname,
round(pl.plannedqty, 2) as planqty, round(pl.plannedprice, 2) as planrate,
round(pl.plannedamt, 2) as planamt
FROM adempiere.c_projectline pl
LEFT JOIN adempiere.c_project pj ON pl.c_project_id = pj.c_project_id
LEFT JOIN adempiere.c_projectphase ph ON pl.c_projectphase_id = ph.c_projectphase_id
LEFT JOIN adempiere.c_projecttask pt ON pl.c_projecttask_id = pt.c_projecttask_id
LEFT JOIN adempiere.m_product pd ON pl.m_product_id = pd.m_product_id
WHERE pl.c_project_id = 1000001 AND pl.ad_client_id = 1000000
ORDER BY ph.c_projectphase_id, pt.c_projecttask_id)
Output is: 11 columns and 16 rows
Query #2:
(SELECT
fa.c_project_id, fa.c_projectphase_id, fa.c_projecttask_id, fa.m_product_id,
pj.name as costprojectname, ph.name as costphasename, pt.name as costtaskname,
pd.name as costprodname,
abs(fa.qty) as costqty, round((fa.amtacctdr/fa.qty), 2) as costrate,
round(sum(fa.amtacctdr), 0) as costamt
FROM adempiere.fact_acct fa
LEFT JOIN adempiere.c_project pj ON fa.c_project_id = pj.c_project_id
LEFT JOIN adempiere.c_projectphase ph ON fa.c_projectphase_id = ph.c_projectphase_id
LEFT JOIN adempiere.c_projecttask pt ON fa.c_projecttask_id = pt.c_projecttask_id
LEFT JOIN adempiere.m_product pd ON fa.m_product_id = pd.m_product_id
WHERE fa.c_project_id = 1000001 AND (fa.gl_category_id = 1000006 OR fa.gl_category_id = 1000005)
AND fa.qty > 0 AND fa.c_project_id is not null
GROUP BY fa.m_product_id, fa.c_project_id, fa.c_projectphase_id, fa.c_projecttask_id,
fa.qty, fa.amtacctdr,
pj.name, ph.name, pt.name, pd.name)
Output is: 11 columns and 6 rows
I want to join these queries horizontally, display all columns but rows should not duplicate. As when I apply union to join them the result shows duplicate rows. How can I cope with this issue?
You should be able to join queries like this:
select * from
(
<your first query here>
) tbl1
join (
<your second query here>
) tbl2
on tbl1.c_project_Id = tbl2.c_project_Id
and tbl1.c_projectphase_Id = tbl2.c_projectphase_Id -- you might add or
and tbl1.c_projecttask_Id = tbl2.c_projecttask_Id -- remove join criteria
and tbl1.m_product_Id = tbl2.m_product_Id -- here