T-SQL Left Join using "or" operator - sql-server

I have the following query where I would like to pull in either or both on a match. There can be more than one ID or HIC for a member. So if the member ID = member ID then pull the max (loaddate) for the most current HIC Likewise if HIC = HIC pull in the member ID with the max (loaddate). I want to include the left join in case a match isn't found for either scenario.
Code:
SELECT
CH1.*
,AVM.MBR_ID
,AVM.HIC
,AVM.MBR_LST_NM
,AVM.MBR_FST_NM
,CAST(AVM.MBR_BIRTH_DT AS DATE) AS 'MBR_BIRTH_DT'
,AVM.LOADDATE
FROM
#CHECK1 CH1
LEFT JOIN
AVRIL.DBO.VW_MBR AVM ON (CH1.HICN = AVM.HIC OR CH1.MEMBER_ID = AVM.MBR_ID)
WHERE
CH1.HEALTH_PLAN = 'AVRIL'
AND AVM.LOADDATE=(SELECT MAX(LOADDATE) FROM AVRIL.DBO.VW_MBR)
Thanks,
Michael

When you use a field from the VW_MBR table in the where clause, it effectively turns the left join into an inner join. Put the condition in the join:
...
FROM #CHECK1 CH1
LEFT JOIN AVRIL.DBO.VW_MBR AVM ON (CH1.HICN = AVM.HIC OR CH1.MEMBER_ID = AVM.MBR_ID)
AND AVM.LOADDATE=(SELECT MAX(LOADDATE) FROM AVRIL.DBO.VW_MBR)
WHERE CH1.HEALTH_PLAN = 'AVRIL'

Here may be an alternative to the first proposed answer, I'm using a custom query as jointure in order to optimize it (I use only the max load dates instead of trying the jointure on every rows of the table).
SELECT CH1.*
,MAVM.MBR_ID
,MAVM.HIC
,MAVM.MAX_LOADDATE
FROM #CHECK1 CH1
LEFT JOIN (SELECT AVM.HIC
,AVM.MBR_ID
MAX(AVM.LOADDATE) AS [MAX_LOADDATE]
FROM AVRIL.DBO.VW_MBR AVM
GROUP BY AVM.HIC, AVM.MBR_ID) MAVM (MAVM.HIC = CH1.HICN
OR MAVM.MBR_ID = CH1.MEMBER_ID)
WHERE CH1.HEALTH_PLAN = 'AVRIL'
I simplified the query to focus on the changes in comparison with the other proposed query. You can still add an INNER JOIN clause to AVRIL.DBO.VM_MBR in order to get additional columns:
...
LEFT JOIN (...) MAVM ...
INNER JOIN AVRIL.DBO.VW_MBR AVM2 ON AVM2.HIC = MAVM.HIC
AND AVM2.MBR_ID = MAVM.MBR_ID
AND AVM2.LOADDATE = MAVM.MAX_LOADDATE
...
So you can use AVM2.xxx for the columns you want to use.
Hope this will help

Related

Does SQL Server CASE expression not do short circuit?

Appropriate if somebody could help us to optimize below query
As per execution plane it seems the else part sub query is always executing, irrespective of conditions.
Won't CASE be short circuited? Why is it executing, even though it is not necessary?
IF OBJECT_ID('#Calculation') IS NOT NULL
DROP TABLE #Calculation;
SELECT
Result.IdDeckungsbeitrag,
Result.wert AS Wert,
REPLACE(#Formula, '<#PackagingCosts> ', Result.wert) AS Kalkulation
INTO
#Calculation
FROM
(SELECT
deck.IdDeckungsbeitrag,
CASE
WHEN lp.ID_VERPACKUNG_2 IS NULL
AND lp.ID_VERPACKUNG_3 IS NULL
THEN vg.VERPACKUNGSKOSTEN_PRO_EINHEIT * deck.Menge
ELSE
(
SELECT SUM(temp.me) * vg.VERPACKUNGSKOSTEN_PRO_EINHEIT
FROM
(
SELECT SUM(gv.MENGE) AS me
FROM dbo.KUNDENRECHNUNG_POSITION krp
LEFT JOIN dbo.LIEFERSCHEIN_POSITION lp
ON lp.ID_LIEFERSCHEIN_POSITION = krp.ID_LIEFERSCHEIN_POSITION
LEFT JOIN dbo.GEBINDE_VERLADEN gv
ON gv.ID_LIEFERSCHEIN_POSITION = lp.ID_LIEFERSCHEIN_POSITION
LEFT JOIN dbo.MATERIAL_BESTAND mb
ON mb.ID_MATERIAL_BESTAND = gv.ID_MATERIAL_BESTAND
LEFT JOIN dbo.MATERIAL_GEBINDE mg
ON mg.ID_MATERIAL_BESTAND = mg.ID_MATERIAL_BESTAND
WHERE mg.CHARGE_NUMMER = deck.Charge
GROUP BY mg.ID_VERPACKUNG
) temp
)
END AS wert
FROM #DeckungsbeitragCalculationPositions_TVP deck
LEFT JOIN dbo.KUNDENRECHNUNG_POSITION krp
ON krp.ID_KUNDENRECHNUNG_POSITION = deck.IdDeckungsbeitrag
LEFT JOIN dbo.LIEFERSCHEIN_POSITION lp
ON lp.ID_LIEFERSCHEIN_POSITION = krp.ID_LIEFERSCHEIN_POSITION
LEFT JOIN dbo.VERPACKUNG vg
ON vg.ID_VERPACKUNG = lp.ID_VERPACKUNG_1
WHERE deck.IdMandant = #Id_Mandant
) Result;
Don't think of it as short-circuit or not. That's a procedural code mindset rather than a set-based mindset.
In SQL, the actual "execution" happens in the realm of table or index scans and seeks, hash matches, sorts, and the like. Pull data from different tables into a working set that will eventually produce the desired relational result.
Not seeing any real or projected execution plan, in this case (no pun intended), I suspect the query optimizer decided it was most efficient to first produce this result set in memory:
SELECT mg.ID_VERPACKUNG, mg.CHARGE_NUMMER, SUM(gv.MENGE) AS me
FROM dbo.KUNDENRECHNUNG_POSITION krp
LEFT JOIN dbo.LIEFERSCHEIN_POSITION lp
ON lp.ID_LIEFERSCHEIN_POSITION = krp.ID_LIEFERSCHEIN_POSITION
LEFT JOIN dbo.GEBINDE_VERLADEN gv
ON gv.ID_LIEFERSCHEIN_POSITION = lp.ID_LIEFERSCHEIN_POSITION
LEFT JOIN dbo.MATERIAL_BESTAND mb
ON mb.ID_MATERIAL_BESTAND = gv.ID_MATERIAL_BESTAND
LEFT JOIN dbo.MATERIAL_GEBINDE mg
ON mg.ID_MATERIAL_BESTAND = mg.ID_MATERIAL_BESTAND
GROUP BY mg.ID_VERPACKUNG, mg.CHARGE_NUMMER
This is the subquery from the ELSE clause, minus the WHERE clause conditions and with additional info added to the SELECT to make the match more effective. If the query optimizer can't be confident of meeting the WHEN clause a high percentage of the time, it might believe producing this larger ELSE set once to match against as needed is more efficient. Put another way, if it thinks it will have to run that subquery a lot anyway, it may try to pre-load it for all possible data.
We don't know enough about your database to suggest real solutions, but indexing around the ID_VERPACKUNG_2, ID_VERPACKUNG_3, and CHARGE_NUMMER fields might help. You might also be able to use a CTE, temp table, or table variable to help Sql Server to a better job of caching this data just once.
If the conditions of where are not met then the else will become active. If this is always the case then you would expect the following to return no rows:
select *
FROM #DeckungsbeitragCalculationPositions_TVP deck
LEFT JOIN dbo.KUNDENRECHNUNG_POSITION krp ON krp.ID_KUNDENRECHNUNG_POSITION = deck.IdDeckungsbeitrag
LEFT JOIN dbo.LIEFERSCHEIN_POSITION lp ON lp.ID_LIEFERSCHEIN_POSITION = krp.ID_LIEFERSCHEIN_POSITION
WHERE lp.ID_VERPACKUNG_2 IS NULL
AND lp.ID_VERPACKUNG_3 IS NULL

To add a condition dynamically in PowerBuilder

I'm new to Power Builder code. I need to add a condition to Join dynamically. Any help is appreciated. Thanks a lot
String szdSQL, psql, sznewsql
szdSQL = "Select A, B, C, D
FROM sy_staging
LEFT OUTER JOIN fd_M
ON sy_staging.id = fd_M.id
LEFT OUTER JOIN gl_M
ON sy_staging.id= gl_M.id AND sy_staging.version = gl_M.version
WHERE sy_staging.year = :lyear AND
sy_staging.location = :llocation "
psql = "Upper(fd_M.code3) = 'SMM' "
In my new query I want to add the condition present in this string variable (psql) in the join as below
sznewsql = " "Select A, B, C, D
FROM sy_staging
LEFT OUTER JOIN fd_M
ON sy_staging.id = fd_M.id AND Upper(fd_M.code3) = 'SMM'
LEFT OUTER JOIN gl_M
ON sy_staging.id= gl_M.id AND sy_staging.version = gl_M.version
WHERE sy_staging.year = :lyear AND
sy_staging.location = :llocation "
Hmmm... That's an interesting case - adding a parameter to the ON clause, not the WHERE clause.
I'd use a datawindow, for sure (because I always do), but I'm not sure you can do that in graphic mode. You might have to convert to syntax, and then just add the new parameter into the ON clause with the ":" syntax.
LEFT OUTER JOIN fd_M
ON sy_staging.id = fd_M.id AND Upper(fd_M.code3) = :newStringParm
LEFT OUTER JOIN gl_M
...
and then your PowerScript would be
dw_1.retrieve( lYear, lLocation, psql )
-Paul Horan-
If you're only going to have those two different SQLs, you could just create two separate datawindows and then dynamically swap out the one used in the datawindow control.

Using Multiple "Layered" SQL Server queries with parameters in Access

I have tried to find answers to this question on the net but am not really getting anywhere.
I tried to do screen shots but don't have enough rep. Anyway.
Here is my current query structure.
Tables:
tblInventoryItems(intSerial, intItem, intStyle) -This is the list of current items that are on inventory(built or unbuilt)
tblLocations(intLocationID, chrLocationName, intLotType)
tblItemStyles(intItemStyleID, intBasic Style)
tblItemList(intItemID, intType, intSubtype, intStyle)
tblCommissions(intBuildEvent, intItemType, intItemSubtype)
tblBuildEvents(intSerial, intBuildEventType, dtEventDate)
First Set of Queries
qryCompletedBarns:
SELECT dbo.tblInventoryItems.intSerial,dbo.tblBuildEvents.dtEventDate
FROM dbo.tblItemList
INNER JOIN dbo.tblItemStyles ON
dbo.tblItemList.intStyle = dbo.tblItemStyles.intBasicStyle
INNER JOIN dbo.tblInventoryItems ON
dbo.tblItemList.intItemID = dbo.tblInventoryItems.intItem AND
dbo.tblItemStyles.intItemStyleID = dbo.tblInventoryItems.intStyle
INNER JOIN dbo.tblCommissions ON
dbo.tblItemList.intSubType = dbo.tblCommissions.intItemSubtype
AND dbo.tblItemList.intType = dbo.tblCommissions.intItemType
INNER JOIN dbo.tblBuildEvents ON
dbo.tblBuildEvents.intBuildEventType = dbo.tblCommissions.intBuildEvent AND
dbo.tblInventoryItems.intSerial = dbo.tblBuildEvents.intSerial
WHERE (dbo.tblCommissions.ynCompletesBarn = 1)
So First we select all items that have a build event that qualifies them as completed. An item can have multiple build events but there is only one that qualifies it as completed
qryCompletedBarnDateFilter:
SELECT qryCompletedBarns.intSerial, qryCompletedBarns.dtEventDate
FROM qryCompletedBarns
WHERE (((qryCompletedBarns.dtEventDate)<=InventoryDate()));
Then we jump to Access and filter those results by a UDF that pulls the criteria for the build date of the item(Saved report definitions are stored in a table).
Now, we have a list of all Inventory items that meet the first criteria, which is that they must be built on or before the Inventory Date that the user selects.
Second set of queries:
qryInventoryLogDateFilter:
SELECT tblHaulLogs.*, tblHaulLogs.dtmHaulDate
FROM tblHaulLogs
WHERE (((tblHaulLogs.dtmHaulDate)<=InventoryDate()));
Get all the Haullogs (or you could call them inventory transactions) that are equal to or older than the InventoryDate criteria.
qryLastLogForBarn:
SELECT t1.intSerial, t1.intHaulType, t1.intDestinationSource, t1.intDestination
FROM qryInventoryLogDateFilter AS t1
LEFT JOIN qryInventoryLogDateFilter AS t2
ON (t1.intLogID < t2.intLogID) AND (t1.intSerial = t2.intSerial)
WHERE t2.intLogID IS NULL;
Get the last inventory transaction for each Inventory Item. This query is actually very fast when executed on the server natively.
qryInventoryCurrentCustomer:
SELECT tblSales.intSerial, tblCustomers.chrFirstName + ' ' + tblCustomers.chrLastName
AS chrCustomerName, tblSales.dtSaleDate
FROM tblSales INNER JOIN tblCustomers ON
tblSales.intCustomer = tblCustomers.intCustID
LEFT OUTER JOIN tblHaulLogs ON
tblSales.intSaleID = tblHaulLogs.intOrigon
WHERE (tblHaulLogs.intHaulType IS NULL) AND (tblSales.bolSaleCancelled = 0)
OR (tblHaulLogs.intHaulType <> 3) AND
(tblSales.intOrderType <4) AND (tblSales.bolSaleCancelled = 0)
GROUP BY tblSales.intSerial, tblCustomers.chrFirstName + ' ' + tblCustomers.chrLastName,
tblSales.dtSaleDate, tblSales.intOrderType;
This query does not actually return an "Inventory Item" but rather checks the sales table and returns a customer name if the inventory item was sold.
Now we finally join the two "sections" and the "Current Customer Query":
SELECT qryCompletedBarnDateFilter.intSerial, qryLastLogForBarn.intHaulType,
IIf(IsNull([intDestination]),7,[intDestination]) AS Location,
qryInventoryCurrentCustomer.chrCustomerName,
qryInventoryCurrentCustomer.dtSaleDate, qryCompletedBarnDateFilter.dtEventDate
FROM (qryCompletedBarnDateFilter
LEFT JOIN qryLastLogForBarn
ON qryCompletedBarnDateFilter.intSerial = qryLastLogForBarn.intSerial)
LEFT JOIN qryInventoryCurrentCustomer
ON qryCompletedBarnDateFilter.intSerial = qryInventoryCurrentCustomer.intSerial
WHERE (((qryLastLogForBarn.intDestinationSource)=1
Or (qryLastLogForBarn.intDestinationSource) Is Null));
Then we join to the "Locations" table to get the name of the inventory item's location, and also filter out a certain type of location.
qryRetailBarnsOnInventory:
SELECT qryBarnsOnInventory.intSerial, qryBarnsOnInventory.Location,
tblLocations.chrLocationName, qryBarnsOnInventory.chrCustomerName,
qryBarnsOnInventory.dtEventDate, qryBarnsOnInventory.intHaulType
FROM tblLocations
INNER JOIN qryBarnsOnInventory
ON tblLocations.intLocationID = qryBarnsOnInventory.Location
WHERE (((tblLocations.intLotType)=1));
The Final Query:
SELECT tblItemStyles.chrItemStyle, tblInventoryItems.intSerial,
tblItemSizeList.intItemSize, tblItemPrices.ccyPrice,
tblInventoryItems.txtOptions, qryRetailBarnsOnInventory.chrCustomerName,
qryRetailBarnsOnInventory.dtEventDate, qryRetailBarnsOnInventory.intHaulType,
qryRetailBarnsOnInventory.chrLocationName, tblItemList.intType,
tblItemList.intSubType, tblItemList.intStyle, tblItemSizes.intItemSizeID,
tblItemStyles.intItemStyleID, tblItemPrices.intPriceSheet,
tblInventoryItems.bolinTransit
FROM tblItemSizeList INNER JOIN (tblItemSizes INNER JOIN
(qryRetailBarnsOnInventory INNER JOIN (((tblItemList INNER JOIN
tblItemPrices ON tblItemList.intItemID = tblItemPrices.intItemID)
INNER JOIN tblItemStyles ON tblItemList.intStyle = tblItemStyles.intBasicStyle)
INNER JOIN tblInventoryItems
ON (tblItemList.intItemID = tblInventoryItems.intItem)
AND (tblItemStyles.intItemStyleID = tblInventoryItems.intStyle))
ON qryRetailBarnsOnInventory.intSerial = tblInventoryItems.intSerial)
ON tblItemSizes.intItemSizeID = tblItemList.intSize)
ON tblItemSizeList.intItemSizeID = tblItemSizes.intSize
WHERE (((tblItemList.intType) Like ItemType())
AND ((tblItemList.intSubType) Like ItemSubType())
AND ((tblItemList.intStyle) Like BasicStyle())
AND ((tblItemSizes.intItemSizeID) Like ItemSize())
AND ((tblItemStyles.intItemStyleID) Like SubStyle())
AND ((tblItemPrices.intPriceSheet)=1)
AND ((tblInventoryItems.bolinTransit)=False)
AND ((IIf(IsNull([intHaulType]),2,3)) Like NewUsed())
AND ((IIf(IsNull([chrCustomerName]),2,3)) Like IsSold())
AND ((qryRetailBarnsOnInventory.Location) Like LotID()));
Summary:
In plain English, here is what I want to happen:
Get all Inventory Items from the inventory items table that were completed on or before the date criteria, then get the last inventory transaction on or before the date criteria for each of those items. And then filter by additional criteria that the user provides
I have the correct results but it is SLOW! Like 10-15 seconds. And we do a tremendous amount of queries every day.
What my idea was is to put this all on SQL Server in sprocs or views. If I do this all with views on SQL server and type manual criteria in, it's blazing fast. The problem I have is that every query requires a parameter. Not just the last one. I can pass parameters for the last query all right with a passthrough query but how do I pass the date criteria parameters for the first query?
EDIT:
Would it be possible to get the date criteria from another table? The criteria is stored in another table in the DB. If I could perform some kind of lookup to get that value and use it as the criteria that would make life really simple.

ibm 1 sql creating - need to add 2 tables

I have following view which is working but not sure how to add 2 tables to join.
This table is adres1 and it will join on the IDENT# and IDSFX# to table
prodta.adres1 called adent# and adsfx#, there I need a col. ads15.
then i also need to get the ship to, row in this adres1. this we get first from the order table, prodta. oeord1 in col. odgrc#. This grc# is 11 pos and is combined 8 and 3 of the ent and suf. these 2 represent the ship to record and looking in same table adres1 (we do have many logical views on them if it's easier, like adres15) we can get col. ADSTTC for the ship to state.
Not sure if can included these 2 new parts to the current view created code below. Please ask if something not clear, it's an old system and somewhat developed convoluted.
CREATE VIEW Prolib.SHPWEIGHTP AS SELECT
T01.IDORD#,
T01.IDDOCD,
T01.IDPRT#,
t01.idsfx#,
T01.IDSHP#,
T01.IDNTU$,
T01.IDENT#,
(T01.IDNTU$ * T01.IDSHP#) AS LINTOT,
T02.IAPTWT,
T02.IARCC3,
T02.IAPRLC,
T03.PHVIAC,
T03.PHORD#,
PHSFX#,
T01.IDORDT,
T01.IDHCD3
FROM PRODTA.OEINDLID T01
INNER JOIN PRODTA.ICPRTMIA T02 ON T01.IDPRT# = T02.IAPRT#
INNER JOIN
(SELECT DISTINCT
PHORD#,
PHSFX#,
PHVIAC,
PHWGHT
FROM proccdta.pshippf) AS T03 ON t01.idord# = T03.phord#
WHERE T01.IDHCD3 IN ('MDL','TRP')
I'm not exactly clear on what you're asking, and it looks like some of the column-names are missing from your description, but this should get you pretty close:
CREATE VIEW Prolib.SHPWEIGHTP AS
SELECT T01.IDORD#,
T01.IDDOCD,
T01.IDPRT#,
t01.idsfx#,
T01.IDSHP#,
T01.IDNTU$,
T01.IDENT#,
( T01.IDNTU$ * T01.IDSHP# ) AS LINTOT ,
T02.IAPTWT,
T02.IARCC3,
T02.IAPRLC,
T03.PHVIAC,
T03.PHORD#,PHSFX#,
T01.IDORDT,
T01.IDHCD3,
t04.ads15
FROM PRODTA.OEINDLID T01
INNER JOIN PRODTA.ICPRTMIA T02
ON T01.IDPRT# = T02.IAPRT#
INNER JOIN (SELECT DISTINCT
PHORD#,
PHSFX#,
PHVIAC,
PHWGHT
FROM proccdta.pshippf) AS T03
ON t01.idord# = T03.phord#
JOIN prodta.adres1 as t04
on t04.adent# = t01.adent#
and t04.adsfx# = t01.adsfx#
JOIN prodta.oeord1 t05
on t05.odgrc# = T01.IDENT# || T01.SUFFIX
WHERE T01.IDHCD3 IN ('MDL','TRP')
Let me know if you need more details.
HTH !

How to convert access query to sql server query string?

how to converse access query to sql server query string by programing?
example for access query string
SELECT dbo_VNMST.VISITDATE, dbo_VNTREAT.TREATMENTCODE, dbo_VNMST.HN, dbo_VNMST.VN, dbo_VNTREAT_1.TREATMENTCODE, Count(dbo_VNMST.HN) AS CountOfHN, dbo_PATIENT_NAME.SUFFIX, Mid([firstname],2) AS FIRSTNAME1, Mid([lastname],2) AS LASTNAME1, (FIRSTNAME1+' '+LASTNAME1) AS FULLNAME
FROM (((dbo_VNMST INNER JOIN dbo_VNTREAT ON (dbo_VNMST.VISITDATE = dbo_VNTREAT.VISITDATE) AND (dbo_VNMST.VN = dbo_VNTREAT.VN)) INNER JOIN dbo_VNPRES ON (dbo_VNMST.VISITDATE = dbo_VNPRES.VISITDATE) AND (dbo_VNMST.VN = dbo_VNPRES.VN)) INNER JOIN dbo_VNTREAT AS dbo_VNTREAT_1 ON (dbo_VNMST.VISITDATE = dbo_VNTREAT_1.VISITDATE) AND (dbo_VNMST.VN = dbo_VNTREAT_1.VN)) INNER JOIN dbo_PATIENT_NAME ON dbo_VNMST.HN = dbo_PATIENT_NAME.HN
GROUP BY dbo_VNMST.VISITDATE, dbo_VNTREAT.TREATMENTCODE, dbo_VNMST.HN, dbo_VNMST.VN, dbo_VNTREAT_1.TREATMENTCODE, dbo_PATIENT_NAME.SUFFIX, Mid([firstname],2), Mid([lastname],2)
HAVING (((dbo_VNMST.VISITDATE) Between #9/1/1466# And #9/14/1466#) AND ((dbo_VNTREAT.TREATMENTCODE)="3964") AND ((dbo_VNTREAT_1.TREATMENTCODE)="92H") AND ((dbo_PATIENT_NAME.SUFFIX)=0));
In addition to what Kane posted, you'll also need to replace the underscore ("_") between dbo and the table name with a period ("."), e.g.:
SELECT dbo_VNMST.VISITDATE
will become
SELECT dbo.VNMST.VISITDATE
You'll need to use the SUBSTRING function instead of the MID function, replace double quotes with a single quote and remove the hash (#) identifier for your BETWEEN statement.

Resources