Left join two tables, and then append only new rows to table - sql

I'm trying to take all records from tblForecast and the matching records from tblOpenJobs and append them to tblWorkingTable, but only if the [Job #] does not yet exist in tblWorkingTable.
The first part (through the first Left Join) works fine, but the second left join and Where statement fail with a Syntax error:
Syntax error (missing operator) in query expression 'A.[Job #]= B.[Job #] LEFT JOIN tblWorkingTable AS C ON A.[Job #] = C.[Job#'.
I'm pretty new to SQL, so I'm not sure where I'm going wrong. I could probably get it to work with two separate queries, but it would be really ideal to get it all to work in one.
INSERT INTO tblWorkingTable ( [Rec'd], ForecastMonth, [Ship Week], [Commit Date], [Job #], Customer, [Part #], Released, [Forecast Qty], [Actual Qty], Shipped, [Sales Price], [Sales Value], Invoice, Comments )
SELECT B.[Rec'd], A.ForecastMonth, A.[Ship Week], A.[Commit Date], A.[Job #], A.Customer, A.[Part #], B.Released, A.Qty AS [Forecast Qty], B.Qty AS [Actual Qty], B.Shipped, A.[Sales Price], A.[Sales Value], A.Invoice, A.Comments
FROM tblForecast AS A
LEFT JOIN tblOpenJobs AS B ON A.[Job #] = B.[Job #]
LEFT JOIN tblWorkingTable AS C ON A.[Job #] = C.[Job #]
Where ((C.[Job #]) is Null);
And yes, I know, there shouldn't be special characters in those field names. I need to assign those a different name during the data import.

MS Access requires parentheses around joins. Try this:
INSERT INTO tblWorkingTable ( [Rec'd], ForecastMonth, [Ship Week], [Commit Date], [Job #], Customer, [Part #], Released, [Forecast Qty], [Actual Qty], Shipped, [Sales Price], [Sales Value], Invoice, Comments )
SELECT B.[Rec'd], A.ForecastMonth, A.[Ship Week], A.[Commit Date], A.[Job #], A.Customer, A.[Part #], B.Released, A.Qty AS [Forecast Qty],
B.Qty AS [Actual Qty], B.Shipped, A.[Sales Price], A.[Sales Value], A.Invoice, A.Comments
FROM (tblForecast AS A LEFT JOIN
tblOpenJobs AS B
ON A.[Job #] = B.[Job #]
) LEFT JOIN
tblWorkingTable AS C
ON A.[Job #] = C.[Job #]
WHERE C.[Job #] is Null;

Related

Incorrect Syntax Left Join subquery with aggregation

I'm trying to run the following query through SQL Server. I keep getting a incorrect syntax error near',' but I can't figure out which comma is incorrect. I'm pretty new to SQL but especially still trying to figure out more complex queries.
SELECT
lastdate.[Date of Record],
billing.[Club Code],
billing.[Club Name],
lastdate.[Member Code with Name],
billing.[Activity Code],
billing.[Category Code],
billing.[Dues Net Amount],
billing.[Dues Gross Amount],
billing.[Member Type Code],
billing.[Member Join Date],
billing.[Member Status Rule Code]
FROM
[dbo].[view_Club_Transactions_0100_(15) Dues_Summary] billing
LEFT JOIN
(MAX(lastdate.[Date of Record]) dor,
lastdate.[Member Code with Name]
FROM
[dbo].[view_Club_Transactions_0100_(15) Dues_Summary] lastdate
GROUP BY
lastdate.[Member Code with Name])
ON
billing.[Member Code with Name]=lastdate.[Member Code with Name]
WHERE
([Member Status Rule Code] = N'ZRESIGN')
AND
([Activity Code] = N'DUES')
Your subquery is missing the SELECT keyword... And an alias too. You also need to align the subquery column alias for the date column with the outer query:
SELECT
lastdate.[Max Date of Record], ---------------> column alias
billing.[Club Code],
...
FROM [dbo].[view_Club_Transactions_0100_(15) Dues_Summary] billing
LEFT JOIN (
SELECT -------------------------------> "SELECT" keyword
MAX([Date of Record]) [Max Date of Record], ---> column alias
[Member Code with Name]
FROM [dbo].[view_Club_Transactions_0100_(15) Dues_Summary]
GROUP BY [Member Code with Name]
) lastdate -------------------------------> subquery alias
ON billing.[Member Code with Name]=lastdate.[Member Code with Name]
WHERE ...
I actually suspect that you can skip the self join and use window functions instead. That could be:
SELECT *
FROM (
SELECT
MAX([Date of Record]) OVER(PARTITION BY [Member Code with Name]) [Max Date of Record],
[Club Code],
[Club Name],
[Member Code with Name],
[Activity Code],
[Category Code],
[Dues Net Amount],
[Dues Gross Amount],
[Member Type Code],
[Member Join Date],
[Member Status Rule Code]
FROM [dbo].[view_Club_Transactions_0100_(15) Dues_Summary]
) t
WHERE [Member Status Rule Code] = N'ZRESIGN' AND [Activity Code] = N'DUES'

Getting Null Value joining 3 tables

Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.
SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
dbo.Supplier.Supplier,
dbo.Supplier.Name,
dbo.Supplier.Status,
dbo.Supplier.AddressCode,
dbo.Supplier.Address,
dbo.Supplier.HouseNo,
dbo.Supplier.Street,
dbo.Supplier.City,
dbo.Supplier.Country,
dbo.Supplier.ZipCode,
dbo.Supplier.StartDate,
dbo.Supplier.CreditLimit,
dbo.Supplier.FinancialGroup,
dbo.Supplier.LastTransactionDate,
dbo.Fact_PurchaseOrder.Company,
ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
dbo.Fact_PurchaseOrder.[Order Quantity],
dbo.Fact_PurchaseOrder.[Per Purchase Unit],
dbo.Fact_PurchaseOrder.[Per Quantity Price],
dbo.Fact_PurchaseOrder.[Purchase price unit],
dbo.Fact_PurchaseOrder.[Total Order Amount],
dbo.Fact_PurchaseOrder.Currency,
dbo.Fact_PurchaseOrder.[Rate Date],
dbo.Fact_PurchaseOrder.[Actual Receipt Date],
dbo.Fact_PurchaseOrder.[Receipt No],
dbo.Fact_PurchaseOrder.[Receipt Sequence],
dbo.Fact_PurchaseOrder.[Received Quantity],
dbo.Fact_PurchaseOrder.[Approved Quantity],
dbo.Fact_PurchaseOrder.[Purchase Office],
dbo.Fact_PurchaseOrder.[Invoice Number],
dbo.Fact_PurchaseOrder.[Invoice Date],
dbo.Fact_PurchaseOrder.[Invoice Quantity],
dbo.Fact_PurchaseOrder.[Invoice Amount],
dbo.Fact_AccountPayables.InvoiceNumber,
dbo.Fact_AccountPayables.Type AS InvoiceType,
dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
dbo.Fact_AccountPayables.AP_Balance_EUR,
dbo.Fact_AccountPayables.[Invoice Amount_EUR],
dbo.Fact_AccountPayables.supplier_key AS EXPR2,
dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
dbo.Fact_AccountPayables.InvoiceNumber,
dbo.Fact_AccountPayables.DueDate,
dbo.Fact_AccountPayables.DocDate,
dbo.Fact_PurchaseOrder.[Order Date],
dbo.Fact_AccountPayables.[Invoice Amount_EUR],
(CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
WHEN dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
(dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
FROM dbo.Supplier
LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order] AND
dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
The output is like this:
Try your Payable table after that FROM Clause and join the other tables by using LEFT JOIN
FROM dbo.Fact_AccountPayables
LEFT JOIN dbo.Fact_PurchaseOrder ON dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order] AND
dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
LRFT JOIN dbo.Supplier ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key AND dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key
You have used not only supplier key, but also PO number and PO line as join criterion with full outer join. If there is no matching entry for these (matching entries for ALL join criteria in the same time) in supplier table you will also see the null values you mentioned.
Just for testing remove temporarily the other join criteria (PO number and line) and leave only the supplier key. Check if you still see the null values in this case.
You're using a FULL join for the Fact_AccountPayables table. This way, all records from Fact_AccountPayables are included even if there are no matches with the other two tables. If you don't want that, use LEFT join instead of FULL join.
SELECT
ISNULL(dbo.Supplier.supplier_key, dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
dbo.Supplier.Supplier,
dbo.Supplier.Name,
dbo.Supplier.Status,
dbo.Supplier.AddressCode,
dbo.Supplier.Address,
dbo.Supplier.HouseNo,
dbo.Supplier.Street,
dbo.Supplier.City,
dbo.Supplier.Country,
dbo.Supplier.ZipCode,
dbo.Supplier.StartDate,
dbo.Supplier.CreditLimit,
dbo.Supplier.FinancialGroup,
dbo.Supplier.LastTransactionDate,
dbo.Fact_PurchaseOrder.Company,
ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order], dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
ISNULL(dbo.Fact_PurchaseOrder.Sequence, dbo.Fact_AccountPayables.Line) AS POSequence,
dbo.Fact_PurchaseOrder.[Order Quantity],
dbo.Fact_PurchaseOrder.[Per Purchase Unit],
dbo.Fact_PurchaseOrder.[Per Quantity Price],
dbo.Fact_PurchaseOrder.[Purchase price unit],
dbo.Fact_PurchaseOrder.[Total Order Amount],
dbo.Fact_PurchaseOrder.Currency,
dbo.Fact_PurchaseOrder.[Rate Date],
dbo.Fact_PurchaseOrder.[Actual Receipt Date],
dbo.Fact_PurchaseOrder.[Receipt No],
dbo.Fact_PurchaseOrder.[Receipt Sequence],
dbo.Fact_PurchaseOrder.[Received Quantity],
dbo.Fact_PurchaseOrder.[Approved Quantity],
dbo.Fact_PurchaseOrder.[Purchase Office],
dbo.Fact_PurchaseOrder.[Invoice Number],
dbo.Fact_PurchaseOrder.[Invoice Date],
dbo.Fact_PurchaseOrder.[Invoice Quantity],
dbo.Fact_PurchaseOrder.[Invoice Amount],
dbo.Fact_AccountPayables.InvoiceNumber,
dbo.Fact_AccountPayables.Type AS InvoiceType,
dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
dbo.Fact_AccountPayables.AP_Balance_EUR,
dbo.Fact_AccountPayables.[Invoice Amount_EUR],
dbo.Fact_AccountPayables.supplier_key AS EXPR2,
dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
dbo.Fact_AccountPayables.InvoiceNumber,
dbo.Fact_AccountPayables.DueDate,
dbo.Fact_AccountPayables.DocDate,
dbo.Fact_PurchaseOrder.[Order Date],
dbo.Fact_AccountPayables.[Invoice Amount_EUR],
CASE
WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
WHEN dbo.Fact_AccountPayables.InvoiceNumber IS NULL THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
END AS ORDERBALANCE,
dbo.Supplier.CreditLimit - (ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR]) AS Availablecredit
FROM
dbo.Supplier
LEFT JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
LEFT JOIN dbo.Fact_AccountPayables ON
dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order] AND
dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
Some of the rows are getting filtered in the Fact_PurchaseOrder, if they dont have supplier. You need to go for FULL OUTER JOIN for all tables, to get data for all rows of AccountPayables, irrespective of whether they have got suppliers or not.
FROM dbo.Supplier
FULL OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
FULL OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order] AND
dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence

Unexpected NULLs in JOIN query

I am using 3 tables in the query: 2 with INNER JOIN and the 3rd with LEFT JOIN.
However, I am getting some NULLrecords while the LEFT JOIN condition is executing. There are coming from the Purchase line(PL_ TABLE)`which should not be the case.
Can any one recommend the change in the query to replace NULL values in the record with actual values?
Sorry, I could not find any option to attach the sample table data.
The Query
SELECT
pih.[PO Number],
pih.[Pre-Assigned No_] as [Invoice No],
pil.[Document No_],
pil.[Description] as [Reason For Discrepency],
pil.[Line No_],
pl.[No_] as [Item No],
pl.[Vendor Item No_],
pl.[Order Date],
pil.[Posting Date],
pil.[Expected Receipt Date],
pih.[Notes] as [Header Notes],
pil.[No_] as [G/L Account No],
pih.[Buy-from Vendor No_],
pih.[Buy-from Vendor Name],
Pil.Quantity as [Inv Qty From InvoiceLine],
pil.[Amount Including VAT] as [Inv Value From InvoiceLine],
pl.Quantity as [PO Quantity From Purchaseline],
pl.[Quantity Received] as [Received Qty From PurchaseLine],
pl.[Quantity Invoiced] as [Invoiced Qty From PurchaseLine] ,
pl.[Amount Including VAT] as [PO Value From PurchaseLine]
FROM
[Purch_ Inv_ Line] pil
INNER JOIN Purch_ Inv_ Header] pih
ON pil.[Document No_] = pih.[No_]
LEFT JOIN [Purchase Line] pl
ON pih.[PO Number]=pl.[Document No_] and pl.[Line No_]=pil.[Line No_]
WHERE
PIL.[Document No_] IN
(
SELECT distinct pil.[Document No_] FROM
Purch_ Inv_ Line] pil
WHERE piL.[No_] in ('700xxx','700xxx','17xxxxx') and pil.[Posting Date] >=getdate()-7
)
AND piL.[Type]='1'
There might be 2 reasons why you are getting NULL values:
Values of columns in [Purchase line] table are actually NULL
There are no matching rows in [Purchase line] table for rows that are NULL. This is how LEFT JOIN works
If you want to get only matching rows, then change LEFT JOIN to INNER JOIN - however then your result set will not contain rows from [Purch_ Inv_ Line] and [Purch_ Inv_ Header] where there are not matching [Purchase line] rows.
If you want to give default values to NULL values you can do it using ISNULL:
ISNULL(pl.[Amount Including VAT], 0) as [PO Value From PurchaseLine]

Ambiguous Column Name with Group By

I am having Ambiguous Column Name "Item" error for the query below. However, I already type in the desired form as parameters are at the beginning of columns.
SELECT
[Country Code],
Item,
[FE SSO],
[Newest Job Number],
[Newest Transaction Date],
Z.ConsignDate AS [ConsignDate],
FROM DailyOnhand
LEFT JOIN
(SELECT
[Job Number],
[Item],
Min([Transaction Day]) AS ConsignDate
FROM vwAllTxns
GROUP BY [Job Number], [Item]) Z
ON vwDailyOnhand_v2.[Newest Job Number] = Z.[Job Number]
AND vwDailyOnhand_v2.[Item] = Z.[Item]
Any help is appreciated.
Thank you!
You need to prefix item in your select with the name/alias of the table it is sourced from.
SELECT
d.[Country Code],
d.Item,
d.[FE SSO],
d.[Newest Job Number],
d.[Newest Transaction Date],
Z.ConsignDate AS [ConsignDate],
FROM DailyOnHand d
LEFT JOIN
(SELECT
v.[Job Number],
v.[Item],
Min(v.[Transaction Day]) AS ConsignDate
FROM vwAllTxns v
GROUP BY v.[Job Number], v.[Item]
) Z
ON d.[Newest Job Number] = Z.[Job Number]
AND d.[Item] = Z.[Item]
Your from specifies DailyOnHand but your on specifies vwDailyOnhand_v2, I removed the later and used an alias instead.
SELECT
[Country Code],
Z.[Item], -- Need to specify which item is source
[FE SSO],
[Newest Job Number],
[Newest Transaction Date],
Z.ConsignDate AS [ConsignDate],
FROM DailyOnhand
LEFT JOIN
(SELECT
[Job Number],
[Item],
Min([Transaction Day]) AS ConsignDate
FROM vwAllTxns
GROUP BY [Job Number], [Item]) Z
ON vwDailyOnhand_v2.[Newest Job Number] = Z.[Job Number]
AND vwDailyOnhand_v2.[Item] = Z.[Item]

I keep getting a "missing operator" error on Access and SQL. Query worked before I tried joining table to itself

SELECT ap.ID, ap.[Adjustment Name], ap.[Adjustment Name Description], ap.[2nd Item Number], [ap].Description, ap.[Unit of Measure], ap.[Effective Date], ap.[Expired Date], MAX( ap.[Factor Value Numeric] ) , ap.[Prc Cls], ap.[Prc Cls Description], ap.[Address Number], ap.[Sales Detail Value 01], ap.[Currency Code], c.[Customer Pricing Rule], c.[Alpha Name]
FROM [Adv Price Query Export] ap
INNER JOIN ( SELECT [Adjustment Name], [2nd Item Number], MAX([Effective Date]), [Factor Value Numeric], [Sales Detail Value 01]
FROM [Adv Price Query Export] ) s ON ((s.[Adjustment Name] = ap.[Adjustment Name]) AND (s.[Effective Date] = ap.[Effective Date]) AND (s.[Sales Detail Value 01] = ap.[Sales Detail Value 01]))
INNER JOIN Customer c ON (ap.[Adjustment Name] = c.[Adjustment Schedule])
WHERE ( ap.[2nd Item Number] = "18500" OR ap.[2nd Item Number] = "185047" OR ap.[2nd Item Number] = "18550" OR ap.[2nd Item Number] = "26004" OR ap.[2nd Item Number] = "55010" )
GROUP BY ap.[Sales Detail Value 01]
Not sure where the error is but you can re-write your query like below
SELECT ap.ID,
ap.[Adjustment Name],
ap.[Adjustment Name Description],
ap.[2nd Item Number],
[ap].Description,
ap.[Unit of Measure],
ap.[Effective Date],
ap.[Expired Date],
MAX( ap.[Factor Value Numeric] ) ,
ap.[Prc Cls],
ap.[Prc Cls Description],
ap.[Address Number],
ap.[Sales Detail Value 01],
ap.[Currency Code],
c.[Customer Pricing Rule],
c.[Alpha Name]
FROM [Adv Price Query Export] ap
INNER JOIN ( SELECT [Adjustment Name],
[2nd Item Number],
MAX([Effective Date]),
[Factor Value Numeric],
[Sales Detail Value 01]
FROM [Adv Price Query Export] ) s
ON s.[Adjustment Name] = ap.[Adjustment Name]
AND s.[Effective Date] = ap.[Effective Date]
AND s.[Sales Detail Value 01] = ap.[Sales Detail Value 01]
INNER JOIN Customer c ON ap.[Adjustment Name] = c.[Adjustment Schedule]
WHERE ap.[2nd Item Number] IN ("18500", "185047", "18550", "26004", "55010" )
GROUP BY ap.[Sales Detail Value 01]