Click here to Skip to main content
15,887,854 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi all,
I want to fill a grid (no hirarchical) where to combine customer data and the last selling item of each customer in a row (getting only the last sellings depending on sells_date).
My idea was

SELECT C.id,C.customerdata,S.id,S.sellsdata FROM dbo.customer AS C LEFT OUTER JOIN (SELECT TOP 1 id,sellsdata FROM dbo.sells ORDER BY sells_date DESC) AS S ON C.id=S.id<br />

Whith this string I get only one selling item and not one item for each.
How does the correct SQL-String look likes ?

tnx in advance
Frank
Posted

1 solution

You should ALWAYS provide the actual fields for each table to avoid misunderstandings.

This should solve the problem...

;WITH LatestSells AS (<br />	SELECT s1.* <br />	FROM dbo.Sells AS s1<br />	INNER JOIN (<br />		SELECT DISTINCT Customer_ID<br />			, (	SELECT TOP 1 Sell_ID <br />				FROM dbo.Sells <br />				WHERE Customer_ID = sx.Customer_ID <br />				ORDER BY Sell_Date DESC <br />			  ) AS Sell_ID<br />		FROM dbo.Sells AS sx<br />	) AS s2 ON s1.Customer_ID = s2.Customer_ID AND s1.Sell_ID = s2.Sell_ID<br />)<br />SELECT c.*, s.*<br />FROM  dbo.Customers			AS c<br />LEFT OUTER JOIN LatestSells AS s<br />ON c.Customer_ID = s.Customer_ID<br />
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900