Hello! I am trying to develop a SQL Server 2005 query but I'm being unsuccessful at the moment. I trying every different approach that I know, like derived tables, sub-queries, CTE's, etc, but I couldn't solve the problem. I won't post the queries I tried here because they involve many other columns and tables, but I will try to explain the problem with a simpler example:
There are two tables:
PARTS_SOLD
andPARTS_PURCHASED
. The first contains products that were sold to customers, and the second contains products that were purchased from suppliers. Both tables contains a foreign key associated with the movement itself, that contains the dates, etc.Here is the simplified schema:
Table PARTS_SOLD
:
part_id
date
- other columns
Table PARTS_PURCHASED
part_id
date
other columns
What I need is to join every row in
PARTS_SOLD
with a unique row fromPARTS_PURCHASED
, chose bypart_id
and the maximum "date
", where the "date
" is equal of before the "date
" column fromPARTS_PURCHASED
. In other words, I need to collect some information from the last purchase event for the item for every event of selling this item.
The problem itself is that I didn't find a way of joining the PARTS_PURCHASED
table with PARTS_SOLD
table using the column "date
" from PARTS_SOLD
to limit the MAX(date)
of the PARTS_PURCHASED
table.
I could have done this with a cursor to solve the problem with the tools I know, but every table has millions of rows, and perhaps using cursors or sub-queries that evaluate a query for every row would make the process very slow.