joining 3 tables in sql server 2012 gives me duplicate records - sql-server

I have three tables joined with the left outer join and I need to check two columns in both tables but in the right table, I got the more than one record from the same column so I want only the value exists to record, not value '0' record.
I have 3 tables
for that, I have made this query result is almost there but it returns duplicate rows.
this is my SQL query
SELECT PWA.DT,
P.MOULDCODE AS DieNo,
T.AssemblyWt AS AWT,
T.WaxWt AS WWt,
T.CoreWt AS CWT
FROM PRCWaxAss PWA
LEFT OUTER JOIN PRC P ON PWA.PRCNO = P.PRCNO
LEFT OUTER JOIN TDCWaxView T ON (P.MOULDCODE = T.DieNo)
AND (P.METALCODE = T.MetalCode
OR T.MetalCode = '0');
and this is my output
"TDC" table and "PRC" table joined with left outer I have compared "die no" and "metal code" in both table if both are matched in PRC table then it will okay but if not matched "metal code" then I need to show record "metal code" value as "0" in TDC. in output image red highlighted row I don't want.
Can anyone help me..thank you in advance.

The OR condition is giving you the multiple line output of what you don't want.
Give this a try and it should give you what you are looking for.
Replace this line (P.METALCODE = T.MetalCode OR T.MetalCode = '0')
With this T.METALCODE = CASE WHEN P.MetalCode = T.MetalCode THEN P.MetalCode ELSE '0' END

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

Updating one table's column in SQL Server from another

I have a table of measurements from weather stations, with station names (in Hebrew):
I also have created a table of those weather stations with their latitudes and longitudes:
I've written a query that should update the first table with the lat/longs from the second, but it's not working:
update t1
set t1.MeasurementLat = t2.Latitude,
t1.MeasurementLong = t2.Longitude
from [dbo].[Measurements] as t1
inner join [dbo].[StationCoords] as t2 on t1.StationName like t2.Station
I think there is a problem with the way the station name is being read, and perhaps something to do with encoding, because this query brings back an empty result, too:
SELECT TOP (5) *
FROM [dbo].[Measurements]
WHERE [StationName] = 'אריאל מכללה';
Any ideas?
Your example names are not the same. Perhaps this will work:
update m
set MeasurementLat = sc.Latitude,
MeasurementLong = sc.Longitude
from dbo.[Measurements] m join
dbo.[StationCoords] sc
on m.StationName like sc.Station + '%';

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.

SQL Server LEFT JOIN

This query has been keeping me busy for the last couple of days. I tried to rewrite it with different ideas but I keep having the same problem. To simplify the problem I put part of my query in a view, this view returns 23 records. Using a left join I would like to add fields coming from the table tblDatPositionsCalc to these 23 records. As you can see I have an additional condition on the tblDatPositionsCalc in order to only consider the most recent records. With this condition it would return 21 records. The join should be on two fields together colAccount and colId.
I simply want the query to return the 23 records from the view and where possible have the information from tblDatPositionsCalc. There is actually only 2 records in the view without corresponding id and account in tblDatPositionsCalc, that means out of the 23 records only 2 will have missing values in the fields coming from the table tblDatPositionsCalc.
The problem with my query is that it only returns the 21 records from tblDatPositionsCalc. I don't understand why. I tried to move the condition on date in just after the JOIN condition but that did not help.
SELECT TOP (100) PERCENT
dbo.vwCurrPos.Account,
dbo.vwCurrPos.Id,
dbo.vwCurrPos.TickerBB,
dbo.vwCurrPos.colEquityCode,
dbo.vwCurrPos.colType,
dbo.vwCurrPos.colCcy,
dbo.vwCurrPos.colRegion,
dbo.vwCurrPos.colExchange,
dbo.vwCurrPos.[Instr Type],
dbo.vwCurrPos.colMinLastDay,
dbo.vwCurrPos.colTimeShift,
dbo.vwCurrPos.Strike,
dbo.vwCurrPos.colMultiplier,
dbo.vwCurrPos.colBetaVol,
dbo.vwCurrPos.colBetaEq,
dbo.vwCurrPos.colBetaFloor,
dbo.vwCurrPos.colBetaCurv,
dbo.vwCurrPos.colUndlVol,
dbo.vwCurrPos.colUndlEq,
dbo.vwCurrPos.colUndlFut,
tblDatPositionsCalc_1.colLots,
dbo.vwCurrPos.[Open Positions],
dbo.vwCurrPos.colListMatShift,
dbo.vwCurrPos.colStartTime,
tblDatPositionsCalc_1.colPrice,
tblDatPositionsCalc_1.colMktPrice,
dbo.vwCurrPos.colProduct,
dbo.vwCurrPos.colCalendar,
CAST(dbo.vwCurrPos.colExpiry AS DATETIME) AS colExpiry,
dbo.vwCurrPos.colEndTime,
CAST(tblDatPositionsCalc_1.colDate AS datetime) AS colDate,
dbo.vwCurrPos.colFund,
dbo.vwCurrPos.colExchangeTT,
dbo.vwCurrPos.colUserTag
FROM dbo.vwCurrPos
LEFT OUTER JOIN dbo.tblDatPositionsCalc AS tblDatPositionsCalc_1
ON tblDatPositionsCalc_1.colId = dbo.vwCurrPos.Id
AND tblDatPositionsCalc_1.colAccount = dbo.vwCurrPos.Account
WHERE (tblDatPositionsCalc_1.colDate =
(SELECT MAX(colDate) AS Expr1 FROM dbo.tblDatPositionsCalc))
ORDER BY
dbo.vwCurrPos.Account,
dbo.vwCurrPos.Id,
dbo.vwCurrPos.colEquityCode,
dbo.vwCurrPos.colRegion
Any idea what might cause the problem?
(Option 1) DrCopyPaste is right so your from clause would look like:
...
FROM dbo.vwCurrPos
LEFT OUTER JOIN dbo.tblDatPositionsCalc AS tblDatPositionsCalc_1
ON tblDatPositionsCalc_1.colId = dbo.vwCurrPos.Id
AND tblDatPositionsCalc_1.colAccount = dbo.vwCurrPos.Account
and (tblDatPositionsCalc_1.colDate =
(SELECT MAX(colDate) AS Expr1 FROM dbo.tblDatPositionsCalc))
...
reason: the where clause restriction of left joined to column = some expression with fail to return for "null = something" so the row will be removed.
(Option 2) As oppose to pushing code in to additional views where it is harder to maintain you can nest sql select statements;
select
X.x1,X.x2,
Y.*
from X
left join
(select Z.z1 as y1, Z.z2 as y2, Z.z3 as y3
from Z
where Z.z1 = (select max(Z.z1) from Z)
) as Y
on x.x1 = Y.y1 and X.x2 = Y.y2
The advantage here is you check each nested sub query a move out quickly. Although if you still building up more logic check out common table expressions (CTE's) http://msdn.microsoft.com/en-us/library/ms175972.aspx

Retriving data from different tables depending on value in a column

Please pardon me if this question has been asked before, but I simply don't have enough vocabulary to search for what I need as a novice in data bases.
I am using SQL server 2008.
I have a table tblPDCDetails with several columns. One of the columns PDCof holds values :
"A"(for applicant),
"C" for coapplicant,
"G" (for Guarantor).
Another column HolderID holds uniqueid (of holder).
The PDCHolders reside in their respective tables: Applicants in tblApplBasicDetails, CoApllicants in their own table and so on.
Now what I need is how should I retrive the names of holders from their respective tables, depending on the value in PDCof column.
Can I do it at all?
If no how should I work around this?
This should do:
SELECT A.*,
COALESCE(B.Name,C.Name,D.Name) Name
FROM dbo.tblPDCDetails A
LEFT JOIN dbo.tblApplBasicDetails B
ON A.HolderID = B.HolderID
AND A.PDCof = 'A'
LEFT JOIN dbo.tblCoApplBasicDetails C
ON A.HolderID = C.HolderID
AND A.PDCof = 'C'
LEFT JOIN dbo.tblGuarantorlBasicDetails D
ON A.HolderID = D.HolderID
AND A.PDCof = 'G'
The other option is to use a case switch:
Select case Main.PDCof
when 'A' then (select HolderID from Applicants where main.value = value)
when 'C' then (select HolderID from CoApplicants where main.value = value)
when 'G' then (select HolderID from Guarantor where main.value = value)
end
,main.*
from tblPDCDetails main
Depends on whether you run this a few times a day, or a few thousand times an hour

Resources