Incorrect Syntax Left Join subquery with aggregation - sql

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'

Related

Can't find error with MS Access SQL FROM Clause Syntax

Select distinct [Doc Type], [Customer Number], count([Customer Number]) , [T] From (
Select distinct A.[Customer Number] & A.[Membership Number], A.[Customer Number] , B.[Doc Type ], B.[SumOpenAmount] From(
SELECT distinct [Doc Type] , [Customer Number], Sum([Open Amount]) as T FROM Data Where [Doc Type] = 'RU')B, [Data] A
Where B.[Customer Number] = A.[Customer Number] Group by [Doc Type])
group by [Doc Type], [Customer Number]
having count([Customer Number]) = 1
Throwing an Error that Doc Type could refer to more than 1 table listed in the from clause of your SQL Statement
Currently, your query has a number of syntax and suboptimal issues:
GROUP BY: In aggregate queries that contain non-aggregated columns in SELECT clause, GROUP BY must be used. Some dialects allow GROUP BY columns to be omitted but not Access SQL. Also, DISTINCT is not necessary for GROUP BY.
ALIASES: Whenever subqueries and joins are utilized, always use table aliases to avoid name collision for both derived tables and column aliases for all expressions. Additionally, avoid A, B, C ... for more informative aliases including T. See Bad Habits to Kick : Using table aliases like (a, b, c) or (t1, t2, t3).
EXPLICIT JOIN: Use the current ANSI SQL standard of explicit joins and not the outdated implicit joins that use WHERE. See Explicit vs implicit SQL joins.
Therefore, consider following adjustments that employ the above guidelines.
SELECT [doc type]
, [customer number]
, COUNT([customer number]) As CountCustomerNumber -- ALIAS ADDED
, SUM([SumOpenAmount]) As TotalOpenAmount -- AGGREGATED COLUMN
FROM
(SELECT d.[customer number] & d.[membership number] AS CustMemb -- ALIAS ADDED
, d.[customer number]
, agg.[doc type]
, SUM(agg.[TotalSubOpenAmount]) AS SumOpenAmount -- AGGREGATED COLUMN
FROM (SELECT [doc type]
, [customer number]
, SUM([open amount]) AS TotalSubOpenAmount -- INFORMATIVE ALIAS
FROM data
WHERE [doc type] = 'RU'
GROUP BY [doc type]
, [customer number]
) agg -- INFORMATIVE ALIAS
INNER JOIN [data] d -- INNER JOIN USED
ON d.[customer number] = agg.[customer number]
GROUP BY d.[customer number] & d.[membership number] -- GROUP BY COLUMNS ADDED
, d.[customer number]
, agg.[doc type]
) AS sub -- ALIAS ADDED
GROUP BY [doc type]
, [customer number]
HAVING COUNT([customer number]) = 1
Note: Since Access does not support comments in queries. Remove all -- messages before running.
It appears that the B.[DOC TYPE ] in the sub-query has an extra space in the field name.
Also, the sub-query does not reference the inner sub-query's [T] field and as such it will not be available to the main query unless it is in the Data table.
Finally, the outer sub-query's group by does not specify which data source the [Doc Type] is coming from for the grouping.
Try this
Select distinct
[Doc Type],
[Customer Number],
count([Customer Number]),
[T]
From
(
Select
distinct A.[Customer Number] & A.[Membership Number],
A.[Customer Number] ,
B.[Doc Type],
B.[T]
From
(
SELECT distinct
[Doc Type] ,
[Customer Number],
Sum([Open Amount]) as T
FROM
Data
Where [Doc Type] = 'RU'
)B,
[Data] A
Where B.[Customer Number] = A.[Customer Number]
Group by B.[Doc Type]
)
group by [Doc Type], [Customer Number]
having count([Customer Number]) = 1
So, this is a good reason to do aliasing. I think what's happening is your innermost (data) subquery is returning doctype (becomes b as part of the outer subquery), and a also has a doc type. You can also remove the inner Group By clause, because it's done on the outermost query; the results should be the same.
I also noticed that you do this: A.[Customer Number] & A.[Membership Number] and then don't do anything with the column. If you want to do something with that, you should name the Column. I named it CMN below, you can pick whatever you want.
Am I correct that you're also doing an implicit JOIN with the line ) as B, [Data] A? If so, you should consider making that explicit, or you may end up with undesired matches.
If that's what you want, do this:
-- as B, [Data] A
++ as B LEFT JOIN [Data] as A on a.[Customer Number] = b.[Customer Number]
This way, you can get rid of your Where B.[Customer Number] = A.[Customer Number] line (after testing, of course), and you'll end up with a more explicitly defined JOIN. See bottom for what that looks like.
The first Group by [Doc Type] is what's tripping you up.
When referring to fields, it's my personal preference to always add an alias unless I'm only working with a simple oneliner, with one table/view, even if there aren't any fields with similar names, because I usually end up with duplicate names in the future. Even then, I try to add aliases, because then later if I decide I want to add more fields/tables it doesn't make me re-factor the whole thing.
Try this (if you're not doing implicit JOIN):
Select distinct c.[Doc Type], c.[Customer Number], c.CMN, count(c.[Customer Number]) , c.[T]
From (
Select distinct (A.[Customer Number] & A.[Membership Number]) as CMN, A.[Customer Number] , B.[Doc Type], B.[SumOpenAmount]
From(
SELECT distinct d.[Doc Type] , d.[Customer Number], Sum(d.[Open Amount]) as T
FROM Data as d
Where d.[Doc Type] = 'RU'
) as B, [Data] A
Where B.[Customer Number] = A.[Customer Number]
) as C
group by C.[Doc Type], C.[Customer Number], C.CMN
having count(C.[Customer Number]) = 1
Do this if you want to have an explicit JOIN (recommended):
Select distinct c.[Doc Type], c.[Customer Number], c.CMN, count(c.[Customer Number]) , c.[T]
From (
Select distinct (A.[Customer Number] & A.[Membership Number]) as CMN, A.[Customer Number] , B.[Doc Type], B.[SumOpenAmount]
From(
SELECT distinct d.[Doc Type] , d.[Customer Number], Sum(d.[Open Amount]) as T
FROM Data as d
Where d.[Doc Type] = 'RU'
) as B
LEFT JOIN [Data] as A on a.[Customer Number] = b.[Customer Number]
) as C
group by C.[Doc Type], C.[Customer Number], C.CMN
having count(C.[Customer Number]) = 1
(Removed extra spaces)

SQL Sub-Query from 2 Access Queries

I have two queries that I would like to combine into one query using a subquery but I have not able to figure out the right syntax to create the subquery.
Query B is the query that needs to be referenced for Query A to work properly.
Any assistance would be helpful as I am just starting my education on Transact-SQL.
--These two queries are being migrated over from Access as separate queries--
QUERY A:
SELECT Shipment.[Shipment Description], Shipment.[Load ID], Shipment.[Origin Name], Shipment.[Origin City], Shipment.[Origin State], Shipment.[Origin Zip], Shipment.[Origin Country], Shipment.[Destination Name], TMS_Shipment.[Destination State], Shipment.[Destination City], Shipment.[Destination Zip], Shipment.[Destination Country], Shipment.[Pickup To Date/Time], Shipment_Container.Pallets, Shipment_Container.Pieces, [QUERY B].[SumOfReference Number] AS 'Original Number of Pieces', Shipment_Container.Length, Shipment_Container.Width, Shipment_Container.Height, Shipment_Container.[Scaled Weight], Shipment_Container.[Stackability Indicator], Month([Shipment].[Pickup To Date/Time]) AS [Month], Year([Shipment].[Pickup To Date/Time]) AS [Year], [Shipment_Container].[Scaled Weight]/42000 AS [Weight Utilization],Round((100/[Width]),0) AS [# Wide], Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0) AS [# Long], Load.[Service Code], (((Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0))*[Shipment_Container].[Length])/(629*0.85)) AS Cube, Shipment.[Party Responsible for Freight cost], Load.[Number of Stops]
Into Qry_Utilization
FROM (Load INNER JOIN (Shipment_Container INNER JOIN Shipment ON Shipment_Container.[Shipment Description] = Shipment.[Shipment Description]) ON Load.[Load ID] = Shipment.[Load ID]) INNER JOIN [QUERY B] ON Shipment_Container.[Shipment Description] = [QUERY B].[Shipment Description]
WHERE (((Shipment_Container.Length)>1) AND ((Shipment_Container.Width)>1) AND ((Shipment_Container.Height)>1) AND ((Load.[Service Code])='TL' Or (Load.[Service Code])='SPTL' Or (Load.[Service Code])='SPFB' Or (Load.[Service Code])='TLMR'));
QUERY B:
(SELECT Shipment_Container_Reference.[Shipment Description], Shipment_Container_Reference.[Reference Type Desc], Sum(Shipment_Container_Reference.[Reference Number]) AS [SumOfReference Number]
FROM Shipment_Container_Reference
GROUP BY Shipment_Container_Reference.[Shipment Description], Shipment_Container_Reference.[Reference Type Desc]
HAVING (((Shipment_Container_Reference.[Reference Type Desc]) Like '*number of pieces*')))
MSAccess, at least when I was using it, did not properly support subqueries, so you had to do stuff like you've shown; in most cases converting it to SQL is just a matter of changing something like this
SELECT stuff
FROM TableA
INNER JOIN QueryB ON blah
to
SELECT stuff
FROM TableA
INNER JOIN (
SELECT other_stuff
FROM TableB
WHERE blahB
) AS QueryB ON blah`
Other than that
you'll need to convert any * wildcards to % wildcards
if you really are using MySQL (as your current tagging suggests), you will need to replace your [ and ] field delimiters with ` (the unshifted ~ key)
When you need to execute one query (B in this case) and then use its results on another query (A in this case) then the SQL standard offers you Common Table Expression (CTEs).
In your case the query (with the CTE) should take the form:
with b as (
select ... -- all your SQL select here
)
select ... from a join b ... -- note that here you can use any table, as well as B
In your case (added some formatting):
with b as
(
SELECT
Shipment_Container_Reference.[Shipment Description],
Shipment_Container_Reference.[Reference Type Desc],
Sum(Shipment_Container_Reference.[Reference Number]) AS [SumOfReference Number]
FROM Shipment_Container_Reference
GROUP BY Shipment_Container_Reference.[Shipment Description],
Shipment_Container_Reference.[Reference Type Desc] HAVING
(
(
(
Shipment_Container_Reference.[Reference Type Desc]
)
Like '*number of pieces*'
)
)
)
SELECT
Shipment.[Shipment Description],
Shipment.[Load ID],
Shipment.[Origin Name],
Shipment.[Origin City],
Shipment.[Origin State],
Shipment.[Origin Zip],
Shipment.[Origin Country],
Shipment.[Destination Name],
TMS_Shipment.[Destination State],
Shipment.[Destination City],
Shipment.[Destination Zip],
Shipment.[Destination Country],
Shipment.[Pickup To Date/Time],
Shipment_Container.Pallets,
Shipment_Container.Pieces,
[QUERY B].[SumOfReference Number] AS 'Original Number of Pieces',
Shipment_Container.Length,
Shipment_Container.Width,
Shipment_Container.Height,
Shipment_Container.[Scaled Weight],
Shipment_Container.[Stackability Indicator],
Month([Shipment].[Pickup To Date/Time]) AS [Month],
Year([Shipment].[Pickup To Date/Time]) AS [Year],
[Shipment_Container].[Scaled Weight]/42000 AS [Weight Utilization],
Round((100/[Width]),0) AS [# Wide],
Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0) AS [# Long],
Load.[Service Code],
(((Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0))*[Shipment_Container].[Length])/(629*0.85)) AS Cube,
Shipment.[Party Responsible for Freight cost],
Load.[Number of Stops] Into Qry_Utilization
FROM
(
Load
INNER JOIN
(
Shipment_Container
INNER JOIN Shipment ON Shipment_Container.[Shipment Description] = Shipment.[Shipment Description]
)
ON Load.[Load ID] = Shipment.[Load ID]
)
INNER JOIN [QUERY B] ON Shipment_Container.[Shipment Description] = [QUERY B].[Shipment Description]
WHERE
(
((Shipment_Container.Length)>1)
AND ((Shipment_Container.Width)>1)
AND ((Shipment_Container.Height)>1)
AND
(
(
Load.[Service Code]
)
='TL' Or
(
Load.[Service Code]
)
='SPTL' Or (Load.[Service Code])='SPFB' Or (Load.[Service Code])='TLMR'
)
)
;
Please note that this query is not 100% correct in Transact-SQL, since it still has some MS-Access (non-standard) quirks.

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

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;

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]