BigQuery Left Join on Revenue Data - google-bigquery

I'm trying to run a LEFT join in BQ where I'm trying to join in some product classifications to the transactions data, but the revenue figures I end up with are much higher than the actual output. Can anybody see any glaring mistake I've made?
`with transactions as (
select
transaction_date,
retail_unit_code,
order_no,
line_type_code,
item_no,
item_type,
delivery_method,
customer_type,
sales_channel,
created_gross_quantity as created_gross_quantity,
created_sales_gross_amount_euro as created_sales_gross_amount_euro
from `sales.dataset`
),
item_data as (
select
item_no,
item_name,
item_type,
item_classification_1,
item_classification_2,
item_classification_3
from `item.classification.lookup`
group by 1,2,3,4,5,6)
select
t.transaction_date,
t.retail_unit_code,
t.order_no,
t.line_type_code,
t.item_no,
t.item_type,
t.delivery_method,
t.customer_type,
t.sales_channel,
(t.created_gross_quantity) as gross_quantity,
(t.created_sales_gross_amount_euro) as gross_revenue_euro,
id.item_name,
id.item_classification_1,
id.item_classification_2,
id.item_classification_3,
from transactions t
left join item_data id
on t.item_no = id.item_no and t.item_type = id.item_type`
I've tried setting SUM for the metrics as well, but that, funnily enough, doesn't make any difference...

Related

Joining multiple CTEs

I am working on a database of a large retail store.
I have to query data from multiple tables to get numbers such as revenue, raw proceeds and compare different time periods.
Most of it is quite easy but I was struggling to work out a way of joining multiple CTEs.
I made a fiddle so you know what I am talking about.
I simplified the structure a lot and left out quite a few columns in the subqueries because they do not matter in this case.
As you can see every row in every table has country and brand in it.
The final query has to be grouped by those.
What I first tried was to FULL JOIN all the tables, but that didn't work in some cases as you can see here: SQLfiddle #1. Note the two last rows which did not group correctly.
Select Coalesce(incoming.country, revenue.country, revcompare.country,
openord.country) As country,
Coalesce(incoming.brand, revenue.brand, revcompare.brand,
openord.brand) As brand,
incoming.OrdersNet,
openord.OpenOrdersNet,
revenue.Revenue,
revenue.RawProceeds,
revcompare.RevenueCompare,
revcompare.RawProceedsCompare
From incoming
Full Join openord On openord.country = incoming.country And
openord.brand = incoming.brand
Full Join revenue On revenue.country = incoming.country And
revenue.brand = incoming.brand
Full Join revcompare On revcompare.country = incoming.country And
revcompare.brand = incoming.brand
Group By incoming.OrdersNet,
openord.OpenOrdersNet,
revenue.Revenue,
revenue.RawProceeds,
revcompare.RevenueCompare,
revcompare.RawProceedsCompare,
incoming.country,
revenue.country,
openord.country,
revcompare.country,
incoming.brand,
revenue.brand,
revcompare.brand,
openord.brand
Order By country,
brand
I then rewrote the query keeping all the CTEs. I added another CTE (basis) which UNIONs all the possible country and brand combinations and left joined on that one.
Now it works fine (check it out here -> SQLfiddle #2) but it just seems so complicated. Isn't there an easier way to achieve this? The only thing I probably won't be able to change are the CTEs as in real life they are way more complex.
WITH basis AS (
SELECT Country, Brand FROM incoming
UNION
SELECT Country, Brand FROM openord
UNION
SELECT Country, Brand FROM revenue
UNION
SELECT Country, Brand FROM revcompare
)
SELECT
basis.Country,
basis.Brand,
incoming.OrdersNet,
openord.OpenOrdersNet,
revenue.Revenue,
revenue.RawProceeds,
revcompare.RevenueCompare,
revcompare.RawProceedsCompare
FROM basis
LEFT JOIN incoming On incoming.Country = basis.Country AND incoming.Brand = basis.Brand
LEFT JOIN openord On openord.Country = basis.Country AND openord.Brand = basis.Brand
LEFT JOIN revenue On revenue.Country = basis.Country AND revenue.Brand = basis.Brand
LEFT JOIN revcompare On revcompare.Country = basis.Country AND revcompare.Brand = basis.Brand
Thank you all for your help!
Since you only work with two tables, orders and rev, consider conditional aggregation by moving WHERE conditions to CASE logic for single aggregate query. Also, consider only one CTE for all possible country/brand pairs for LEFT JOIN on the two tables.
WITH cb AS (
SELECT Country, Brand FROM orders
UNION
SELECT Country, Brand FROM rev
)
SELECT cb.Country
, cb.Brand
, SUM(o.netprice) AS OrdersNet
, SUM(CASE
WHEN o.isopen = 1
THEN o.netprice
END) AS OpenOrdersNet
, SUM(CASE
WHEN r.bdate BETWEEN '2020-12-01' AND '2020-12-31'
THEN r.netprice
END) AS Revenue
, SUM(CASE
WHEN r.bdate BETWEEN '2020-12-01' AND '2020-12-31'
THEN r.rpro
END) AS RawProceeds
, SUM(CASE
WHEN r.bdate BETWEEN '2020-11-01' AND '2020-11-30'
THEN r.netprice
END) AS RevenueCompare
, SUM(CASE
WHEN r.bdate BETWEEN '2020-11-01' AND '2020-11-30'
THEN r.rpro
END) AS RawProceedsCompare
FROM cb
LEFT JOIN orders o
ON cb.Country = o.Country
AND cb.Brand = o.Brand
LEFT JOIN rev r
ON cb.Country = r.Country
AND cb.Brand = r.Brand
GROUP BY cb.Country
, cb.Brand
SQL Fiddle

SQL - Only show results for one column in first instance of a duplicated record

I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.
Example of how my query results currently look
Example of how I want the results to look
The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.
I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.
Thanks
EDIT.
If it helps here is my query:
SELECT dbo.Orders.EncryptedOrderId,
dbo.OrderProduct.ProductID,
dbo.OrderProduct.QuantityPerRecipient,
dbo.OrderProduct.NumRecipients,
dbo.OrderProduct.TotalQuantity,
dbo.DocType.Name AS [Product Type],
dbo.ProductGroup_Culture.Name AS [Product Group],
RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.Users.CompanyName AS [Branch Name],
dbo.Users.Department AS Subsidiary,
dbo.Users.Custom1,
dbo.Users.Custom2,
dbo.Users.Custom3,
dbo.Users.Custom4,
dbo.Users.Custom5,
dbo.OrderProduct.TotalPrice,
dbo.Orders.ShippingCharges,
dbo.OrderProduct.OrderProductID,
dbo.FileSubmissionDocument.OriginalFileType,
COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
OP.DialID,
OP.FriendlyValue
FROM OrderProductDialValue OP
LEFT JOIN Dial DI ON DI.DialID = OP.DialID
LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
WHERE PR.ExternalID = 'BCName'
AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('#CUSTOMERNAME' is null
OR '#CUSTOMERNAME' = ''
OR dbo.Store_Culture.Name LIKE '%' + '#CUSTOMERNAME' + '%')
AND dbo.OrderProduct.IsDraft = 0
AND dbo.Orders.IsCart=0
AND dbo.Orders.IsSaveForLater=0
AND (('#DATE' <= dbo.Orders.DateOrderCreated)
OR ('#DATE' IS NULL)
OR ('#DATE'=''))
AND ((DATEADD(day, 1, '#DATE') >= dbo.Orders.DateOrderCreated)
OR ('#DATE' IS NULL)
OR ('#DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC
The query runs through a reporting system on an online portal so the values that show as #CUSTOMERNAME or #DATE are variables based on values given at the time when the report is run.
this may help you
select orderid,
productid,
productvalue,
case ROW_NUMBER() over (partition by orderid order by orderid)
when 1 then deliverycharge
else null end as 'deliverycharge'
from ........
I assume your query looks like
select orderID
, productID
, productValue
, DeliveryCharge
from test_t
order by orderID
, productValue desc
;
and that you want delivery charges listed for the most expensive product of each order.
If supported by your rdbms, you can use the analytic RANK function
select orderID
, productID
, productValue
, DeliveryCharge
, CASE RANK() OVER ( PARTITION BY orderID ORDER BY productValue DESC ) WHEN 1 THEN DeliveryCharge ELSE NULL END r
from test_t
order by orderID
, productValue desc
;
If your rdbms does not support RANK, you can emulate it using a left join with a suitably aggregated copy of your table:
select t.orderID
, t.productID
, t.productValue
, rt.mdc DeliveryCharge
from test_t t
left join (
select orderID
, max(productValue) mp
, max(DeliveryCharge) mdc
from test_t
group by orderID
) rt
on (
rt.orderID = t.orderID
AND rt.mp = t.productValue
)
order by orderID
, productValue desc
;
The tacit assumption is that the delivery charge is by order (which seems reasonable as you wouldn't want to selectively drop it otherwise, right ?).
Moreover, both solutions will produce multiple rows containing the delivery charge per order if that order contains multipleproducts with the same productValue.
Tested on oracle 12c1;

SQL Multiple JOIN Query Not successful

Background
I have three tables: Stock, PurchaseEntry, and SalesEntry.
These tables have the fields ProductName, MRP, LandinPrice and Qty in common.
I need to join these tables in order to get SUM(Qty) in PurchaseEntry and SalesEntry with the same ProductName, MRP, and LandinPrice as Stock.
Problem
I tried using the following query, but the result was not as I desired.
SUM(Qty) of PurchaseEntry Gives some random results, whereas SUM(Qty) of SalesEntry is correct.
But when I use JOIN on PurchaseEntry alone individually, I get the correct values.
Question
How I can get the proper results, and what type of JOINs should be used?
SQL Code
SELECT Stock.ProductName,
Stock.MRP,
Stock.LandinPrice,
SUM(PurchaseEntry.TotalQty)
AS PurchaseQty,
SUM(SalesEntry.Qty)
AS SalesQty
FROM Stock
JOIN PurchaseEntry
ON Stock.ProductName = PurchaseEntry.ProductName
AND Stock.MRP = PurchaseEntry.MRP
AND Stock.LandinPrice = PurchaseEntry.LandinPrice
JOIN SalesEntry
ON Stock.ProductName = SalesEntry.ProductName
AND Stock.MRP = SalesEntry.MRPPrice
AND Stock.LandinPrice = SalesEntry.LandingAmt
GROUP BY Stock.ProductName,
Stock.MRP,
Stock.LandinPrice
Solved:
I tried changing the Query myself. And I got the proper Output that i required. Below is that Query.
SELECT Stock.ProductName,
Stock.MRP,Stock.LandinPrice,
(SELECT SUM(PurchaseEntry.TotalQty)
FROM PurchaseEntry
WHERE Stock.ProductName=PurchaseEntry.ProductName
AND Stock.MRP=PurchaseEntry.MRP
AND Stock.LandinPrice=PurchaseEntry.LandinPrice) AS PurchaseQty,
(SELECT SUM(SalesEntry.Qty)
FROM SalesEntry
WHERE SalesEntry.ProductName=Stock.ProductName
AND SalesEntry.MRPPrice=Stock.MRP
AND SalesEntry.LandingAmt= Stock.LandinPrice ) AS SalesQty
FROM Stock
GROUP BY Stock.ProductName,Stock.MRP,Stock.LandinPrice
You might try something like
SELECT Stock.ProductName,Stock.MRP,Stock.LandinPrice,
(SELECT SUM(PurchaseEntry.TotalQty)
FROM PurchaseEntry
WHERE PurchaseEntry.ProductName=Stock.ProductName
AND PurchaseEntry.MRP=Stock.MRP
AND PurchaseEntry.LandinPrice=Stock.LandinPrice) AS PurchaseQty
(SELECT SUM(SalesEntry.Qty)
FROM SalesEntry
WHERE SalesEntry.ProductName=Stock.ProductName
AND SalesEntry.MRPPrice=Stock.MRP
AND SalesEntry.LandingAmt=Stock.LandinPrice) AS SalesQty
FROM Stock
Your existing query would have PurchaseQty multiplied by the number of sales and SalesQty multiplied by the number of purchases. Of course I'm assuming that the combination of stock ProductName, MRP, and LandinPrice are unique.
SELECT
Stock.ProductName,
Stock.MRP,
Stock.LandinPrice,
SUM(PurchaseEntry.TotalQty) AS PurchaseQty,
Sales.SalesQty
FROM
Stock
INNER JOIN PurchaseEntry ON Stock.ProductName = PurchaseEntry.ProductName AND Stock.MRP = PurchaseEntry.MRP
AND Stock.LandinPrice = PurchaseEntry.LandinPrice
INNER JOIN
(
SELECT SUM(SE.Qty) AS 'SalesQty', SE.ProductName, SE.LandingAmt, SE.MRPPrice
FROM SalesEntry SE INNER JOIN
Stock S ON S.LandinPrice = SE.LandingAmt AND S.MRP = SE.MRPPrice AND S.ProductName = SE.ProductName
GROUP BY SE.ProductName, SE.LandingAmt, SE.MRPPrice
) Sales ON Sales.ProductName = Stock.ProductName AND Sales.LandingAmt = Stock.LandinPrice
AND Sales.MRPPrice = Stock.MRP
GROUP BY
Stock.ProductName,
Stock.MRP,
Stock.LandinPrice

Trying to Calculate Qty on Hand and Value on hand with multiple shipments

I have this query, I have an Acquisitions table (Incoming) and Invoice Table (Outgoing) I am trying to calculate the Value on Hand by taking the AVG dbo.tblAcqDetail.AcqPrice * the QtyOnHand which is figured taking Incoming - Outgoing. When I add a line item on the Acquisitions table that has a different cost for the same item, the AVG is not grouping and showing instead two line items example below. The shipment side works fine with multiple line items...
Product QtyIn QtyOut On_Hand AVGPrice Value_OnHand
Screws 100 30 70 25.0000 1750.0000
Nuts 50 10 40 40.0000 1600.0000
Nuts 100 10 90 50.0000 4500.0000
Bolts 100 20 80 100.000 8000.0000
.
SELECT DISTINCT
dbo.tblProduct.Product ,
SUM(DISTINCT dbo.tblAcqDetail.AcqQuantity) AS QtyIN ,
SUM(DISTINCT dbo.tblInvoiceDetail.InvQuantity) AS QtyOut ,
SUM(DISTINCT dbo.tblAcqDetail.AcqQuantity)
- SUM(DISTINCT dbo.tblInvoiceDetail.InvQuantity) AS On_Hand ,
dbo.tblAcqDetail.AcqPrice ,
dbo.tblAcqDetail.AcqPrice
* ( SUM(DISTINCT dbo.tblAcqDetail.AcqQuantity)
- SUM(DISTINCT dbo.tblInvoiceDetail.InvQuantity) ) AS Value_Hand
FROM dbo.tblAcq
INNER JOIN dbo.tblAcqDetail ON dbo.tblAcq.acqID = dbo.tblAcqDetail.AcqID
INNER JOIN dbo.tblProduct ON dbo.tblAcqDetail.ProductID = dbo.tblProduct.ProductID
INNER JOIN dbo.tblInvoiceDetail ON dbo.tblProduct.ProductID = dbo.tblInvoiceDetail.ProductID
INNER JOIN dbo.tblInvoice ON dbo.tblInvoiceDetail.InvoiceID = dbo.tblInvoice.InvoiceID
GROUP BY dbo.tblProduct.Product ,
dbo.tblAcqDetail.AcqPrice
Basing on PinnyM's answer, you don't need DISTINCT, I re-write your query as following using table alias:
SELECT
P.Product ,
SUM( AcD.AcqQuantity) AS QtyIN ,
SUM( InD.InvQuantity) AS QtyOut ,
SUM( AcD.AcqQuantity)
- SUM( InD.InvQuantity) AS On_Hand ,
AcD.AcqPrice ,
AcD.AcqPrice
* ( SUM(AcD.AcqQuantity)
- SUM( InD.InvQuantity) ) AS Value_Hand
FROM dbo.tblAcq Ac
INNER JOIN dbo.tblAcqDetail AcD ON Ac.acqID = AcD.AcqID
INNER JOIN dbo.tblProduct P ON AcD.ProductID = P.ProductID
INNER JOIN dbo.tblInvoiceDetail InD ON P.ProductID = InD.ProductID
INNER JOIN dbo.tblInvoice Inv ON InD.InvoiceID = Inv.InvoiceID
GROUP BY P.Product ,
AcD.AcqPrice
By reading this query, I don't understand why you need table dbo.tblInvoice, it is not part of aggregation.
The reason you still see different product is because you group by two columns P.Product, AcD.AcqPrice, not only Product, in your return result you can see their combination is unique.
To be mathematically accurate, you should not be using SUM(DISTINCT fieldname), but just SUM(fieldname). Otherwise, it will eliminate entries that happen to have the same quantity.
For that matter, you shouldn't be using DISTINCT at the beginning of your query either, GROUP BY already handles that.
If you believe you have duplicate rows being returned by your JOINs (which you shouldn't really if you're doing it right), wrap them in a subquery using DISTINCT before trying to aggregate.
As an example, a subquery to eliminate duplicates can be written like so:
SELECT
Product ,
SUM(AcqQuantity) AS QtyIN ,
SUM(InvQuantity) AS QtyOut ,
SUM(AcqQuantity)
- SUM(InvQuantity) AS On_Hand ,
AcqPrice ,
AcqPrice
* ( SUM(AcqQuantity)
- SUM(InvQuantity) ) AS Value_Hand
FROM (SELECT DISTINCT
dbo.tblProduct.Product ,
dbo.tblAcqDetail.AcqQuantity,
dbo.tblInvoiceDetail.InvQuantity,
dbo.tblAcqDetail.AcqPrice
FROM
dbo.tblAcqDetail
INNER JOIN dbo.tblProduct ON dbo.tblAcqDetail.ProductID = dbo.tblProduct.ProductID
INNER JOIN dbo.tblInvoiceDetail ON dbo.tblProduct.ProductID = dbo.tblInvoiceDetail.ProductID
INNER JOIN dbo.tblInvoice ON dbo.tblInvoiceDetail.InvoiceID = dbo.tblInvoice.InvoiceID ) productInfo
GROUP BY Product, AcqPrice

How can I select only one record per “person”, per date with an inner join in an MS Access query?

I need to pull data from two tables: Neptune_FN_Analysis and Neptune_prem
There will be 3 fields called readings_miu_id (comparable to a persons name or item #), ReadDate, ReadTime (all of which are in Neptune_FN_Analysis). Some readings_miu_ids have multiple ReadTimes for multiple days but I only want to pull the "last time" entered per readings_miu_id, per day.
I need all readings_miu_ids that have an entry date for the selected range but only the last ReadTime entered for each record I am pulling.
My solution so far, based on one table is:
SELECT readings_miu_id, Reading, ReadDate, ReadTime, MIUwindow, SN, Noise, RSSI, OriginCol, ColID, Ownage
FROM analyzed AS A
WHERE ReadDate Between #4/21/2009# and #4/29/2009#
AND ReadTime=
(SELECT TOP 1 analyzed.ReadTime FROM analyzed
where analyzed.readings_miu_id = A.readings_miu_id
AND analyzed.ReadDate = A.ReadDate
ORDER BY analyzed.ReadTime DESC);
When I try to adapt this solution, I can't do the FROM [tableName] as A, INNER JOIN because it gives me an error. The original code that my predecessor made (which is what I am trying to adapt/fix) is as follows:
SELECT readings_miu_id, Reading, ReadDate,Format([MIUtime],'hh:mm:ss') AS
ReadTime, MIUwindow, SN, Noise, RSSI, ColRSSI, MIURSSI, Firmware, CFGDate, FreqCorr,
Active, MeterType, OriginCol, ColID, Ownage, SiteID, PremID, Neptune_prem.prem_group1,
Neptune_prem.prem_group2, ReadID
INTO analyzed
FROM Neptune_FN_Analysis INNER JOIN
Neptune_prem ON Neptune_FN_Analysis.PremID = Neptune_prem.premice_id
WHERE SiteID = 36801 and ReadDate BETWEEN #04/21/09# AND #04/27/09#
and OriginCol = 'US 29' and ColID = 1 and ColID <> 0 and Active = 'Y'
I don't quite get all of what you're trying to do, but if you inner join on a subquery which gets the MAX of date, it could eliminate all the records where the date was not the max
SELECT readings_miu_id, Reading, ReadDate, ReadTime, MIUwindow, SN,
Noise, RSSI, OriginCol, ColID, Ownage
FROM analyzed
INNER JOIN
(SELECT [whatever the id common to all like records is] as likeID, MAX(analyzed.ReadTime) as latestDate
FROM analyzed
GROUP BY likeID) AS maxDate ON analyzed.likeID=maxDate.likeID AND analyzed.latestDate = maxDate.latestDate
WHERE ReadDate Between #4/21/2009# and #4/29/2009#
modify as needed
I would try something like this:
SELECT a.readings_miu_id, a.Reading, a.ReadDate, a.ReadTime, a.MIUwindow, a.SN, a.Noise, a.RSSI, a.OriginCol, a.ColID, a.Ownage
FROM analyzed AS A INNER JOIN
(SELECT max(ReadTime) as MaxReadTime,readings_miu_id FROM analyzed
WHERE ReadDate Between #4/21/2009# and #4/29/2009#
GROUP BY readings_miu_id) as B
on a.readings_miu_id = b.readings_miu_id and a.MaxReadTime = b.ReadTime
SELECT
<your columns>
FROM
Neptune_FN_Analysis A1
INNER JOIN Neptune_prem ON
P.premice_id = A1.PremID
LEFT OUTER JOIN Neptune_FN_Analysis A2 ON
A2.readings_miu_id = A1.readings_miu_id AND
A2.ReadDate = A1.ReadDate AND
A2.ReadTime > A1.ReadTime
WHERE
A2.readings_miu_id IS NULL AND
<add any additional criteria here>
I'm not sure what you imply by specifying "INNER JOIN" this time around. Other answers use a subquery, so here's a an example using two INNER JOINs and no subquery. Rather than getting my head around your schema :) I'm using Northwind to return customers and the date of their most recent order:
SELECT C1.CustomerID, C1.CompanyName,
O1.OrderID, O1.OrderDate
FROM (Customers AS C1
INNER JOIN Orders AS O1
ON C1.CustomerID = O1.CustomerID)
INNER JOIN Orders AS O2
ON C1.CustomerID = O2.CustomerID
GROUP
BY C1.CustomerID, C1.CompanyName,
O1.OrderID, O1.OrderDate
HAVING O1.OrderDate = MAX(O2.OrderDate);