SQL Sub-Query from 2 Access Queries - sql

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.

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)

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'

Joining two views

I'm after some help please. I only use ms access and beginning to use SQL I have two views part1 and part2 I can't join them and get any results( I have the results from MS access ( see below results part ) . I need the same results to show in SQL )
Thank you..
View (part1)
select Mvpr.Prefix, Mvpr.SubKey1 AS [Parkers Part Number], Mvpr.SubKey2 AS [Supplier Code], Mvpr.A12 AS [Supplier Part Number], vwProduct.Psupp as part1
FROM vwProduct INNER JOIN Mvpr ON vwProduct.KeyCode = Mvpr.SubKey1
WHERE Mvpr.Prefix ='c'
View (part2)
SELECT dbo.RHeads.Document, RLines.Part, RHeads.Supp, RHeads.[DateTime], RLines.Unit, RLines.CQty, RLines.ClCost, RHeads.POrder, RHeads.Corder, RHeads.Branch as part2
FROM RHeads INNER JOIN RLines ON RHeads.Document = RLines.Document
WHERE RHeads.[DateTime] >= DATEADD(MONTH, -3, GETDATE())
Result
SELECT part1.Document, part1.Part [Parkers Part], part2.[Supplier Part Number], part1.Supp [Supplier Code], part1.Unit [Unit Price], part1.CQty [Qty Recieved], dbo.vwProduct.SI18 Surcharge, part1.POrder, part1.Corder, part1.Branch, part1.DateTime
FROM dbo.vwProduct INNER JOIN part2 INNER JOIN part1 ON part2.[Supplier Code] = part1.Supp AND part2.[Parkers Part Number] = part1.Part ON dbo.vwProduct.KeyCode = part1.Part
GROUP BY part1.Document, part1.Part, part2.[Supplier Part Number], part1.Supp, part1.Unit, part1.CQty, dbo.vwProduct.SI18, part1.POrder, part1.Corder, part1.Branch, part1.DateTime
Based on your SQL in Result section, your View (part2) should be your part1 since columns such as Document, Part, etc. are coming from that and vice versa.
SELECT part1.Document,
part1.Part [Parkers Part],
part2.[Supplier Part Number],
part1.Supp [Supplier Code],
part1.Unit [Unit Price],
part1.CQty [Qty Recieved],
dbo.vwProduct.SI18 Surcharge,
part1.POrder,
part1.Corder,
part1.Branch,
part1.DateTime
FROM dbo.vwProduct
INNER JOIN part1
ON dbo.vwProduct.KeyCode = part1.Part
INNER JOIN part2
ON part2.[Supplier Code] = part1.Supp
AND part2.[Parkers Part Number] = part1.Part
GROUP BY part1.Document,
part1.Part,
part2.[Supplier Part Number],
part1.Supp,
part1.Unit,
part1.CQty,
dbo.vwProduct.SI18,
part1.POrder,
part1.Corder,
part1.Branch,
part1.DateTime

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]

SQL joins and group by with 3 separate tables

I have two separate queries here that I need to make into one query, I'll post the queries, then try to explain what I'm trying to do.
SELECT Distinct I.ITMCDE, V.VNDRCDE, V.VNAME
FROM (SELECT RIGHT(Items.[Item Number], 3) as ITMCDE FROM Items) I,
(SELECT LEFT(Vendors.[Vendor ID], 3) as VNDRCDE,
Vendors.[Vendor Name] as VNAME
FROM Vendors) V
WHERE I.ITMCDE = V.VNDRCDE
In this first one, I simply match up the vendor code with the item code, to get the vendor name that produces the item.
SELECT DISTINCT (Items.[Item Description]), ItemQuantities.[QTY Available],
Items.[Selling U Of M], Items.[Item Number]
FROM ItemQuantities
INNER JOIN Items ON ItemQuantities.[Item Number] = Items.[Item Number]
WHERE Items.[Item Number] LIKE 'WH%'
AND Items.[Item Number] NOT LIKE '%RMW'
In this second one I'm selecting the item description, quantity available from two separate tables (quantity available is in a different table, match them up using the item number)
As you can see, the only correlation between the three tables is the item number, and not even that in the vendors table. The last three characters of the item number correlate with the first three characters of the vendor id... I did not design this setup. I'm just trying to work with it now.
How do I join these two statements into one single statement that will give me the vendor name, item description, Unit of Measure (Selling U of M), and item quantity where the item description is unique?
I think this should work:
SELECT DISTINCT Items.[Item Description],
ItemQuantities.[QTY Available],
Items.[Selling U Of M],
Items.[Item Number],
V.VNAME
FROM ItemQuantities
INNER JOIN Items ON ItemQuantities.[Item Number] = Items.[Item Number]
INNER JOIN Vendors ON
RIGHT(Items.[Item Number], 3) = LEFT(Vendors.[Vendor ID], 3)
WHERE Items.[Item Number] LIKE 'WH%'
AND Items.[Item Number] NOT LIKE '%RMW'
You can join it in:
SELECT DISTINCT (i.[Item Description]), iq.[QTY Available],
i.[Selling U Of M], i.[Item Number],
V.VNDRCDE, V.VNAME
FROM ItemQuantities iq INNER JOIN
Items i
ON iq.[Item Number] = i.[Item Number] left outer join
Vendors v
on LEFT(v.[Vendor ID], 3) = RIGHT(i.[Item Number], 3)
WHERE i.[Item Number] LIKE 'WH%' and
i.[Item Number] NOT LIKE '%RMW'
I am not sure if you intend anything special with the parentheses around i.[Item Description]. The distinct keyword applies to the entire row.
If you want distinct only on the description, then you need to use group by. Something like:
SELECT i.[Item Description],
max(iq.[QTY Available]),
max(i.[Selling U Of M]), max(i.[Item Number]),
max(V.VNDRCDE), max(V.VNAME)
FROM ItemQuantities iq INNER JOIN
Items i
ON iq.[Item Number] = i.[Item Number] left outer join
Vendors v
on LEFT(v.[Vendor ID], 3) = RIGHT(i.[Item Number], 3)
WHERE i.[Item Number] LIKE 'WH%' and
i.[Item Number] NOT LIKE '%RMW'
group by i.[Item Description])
The max() will return the maximum value. If all are the same, then this is a good way to get an "arbitrary" value.
#sgeddes Thank you.
This is what I came up with
SELECT DISTINCT
Item.ITEMNMBR AS [Item Number],
Item.ITEMDESC AS [Item Description],
Item.ITMGEDSC AS [Item Category],
Item.SELNGUOM AS [Unit of Measure],
(SELECT VENDNAME FROM PM00200 WHERE (VENDORID = IV00103.VENDORID)) AS [Vendor Name],
(CASE WHEN Quan.QTYONHND > 0 THEN 'In Stock' ELSE 'Out of Stock' END) AS [Stock Status]
FROM IV00101 AS Item INNER JOIN
IV00102 AS Quan ON Item.ITEMNMBR = Quan.ITEMNMBR INNER JOIN
IV00103 ON Item.ITEMNMBR = IV00103.ITEMNMBR AND Quan.ITEMNMBR = IV00103.ITEMNMBR
WHERE (Item.ITEMNMBR LIKE 'WH%') AND (IV00103.VENDORID NOT LIKE '%MIL')