I need to be able to extract rows for a dataset in SSRS 2008 using TSQL. I am using three tables product, stock, calls. product has a composite key of mfg and part_number and those fields are foreign keys in the other two tables. The calls table creates a row that sums the number of calls for a specific month and represents the month in the format yyyymm. What I want to do is to extract the last call for each part but I want to ignore the current month, so I have this:
select product.mfg, product.part_number, max(calls.yyyymm) last_call
from product inner join stock on product.mfg = stock.mfg
and product.part_number = stock.part_number
left join calls on product.mfg = calls.mfg
and product.part_number = calls.part_number
where stock.onhand > 0 and calls.yyyymm < '201202'
This works ok but there are around 65 records where the only call is in '201202'.
I have tried nullif(max(calls.yyyymm), null) instead of max(calls.yyyymm). I would think that a left join to the calls table would get it done, but it doesn’t seem to. I have also tried a couple of variations of a case statement in the select, namely:
case when max(calls.yyyymm) is not null then max(calls.yyyymm) else null end
What I ultimately want to do is create two data sets, one for in stock parts and one for calls on in stock parts, then use the lookup function in SSRS 2008 to create the report, but I want both sets to generate the same number of rows since this is a moving target. This is not my preferred way of doing this but our parts manager wants me to try to freeze the data at the end of each month, which is why I decided to try ignoring all calls for the current month. For each call in the current month I want to use the next call if it exists and insert null if it doesn’t.
Here is a very small example of data, I think all of the variations are covered.
use tempdb;
GO
CREATE TABLE dbo.product(mfg VARCHAR(32), part_number CHAR(5))
INSERT dbo.product SELECT 'mfg1','12345';
INSERT dbo.product SELECT 'mfg2','98765';
INSERT dbo.product SELECT 'mfg3','A1234';
INSERT dbo.product SELECT 'mfg4','5678A';
CREATE TABLE dbo.stock(mfg VARCHAR(32), part_number CHAR(5), onhand INT);
INSERT dbo.stock SELECT 'mfg1','12345',30;
INSERT dbo.stock SELECT 'mfg2','98765', 1;
INSERT dbo.stock SELECT 'mfg3','A1234', 9;
INSERT dbo.stock SELECT 'mfg4','5678A', 0;
CREATE TABLE dbo.calls(mfg VARCHAR(32), part_number CHAR(5), yyyymm CHAR(6));
INSERT dbo.calls SELECT 'mfg1','12345','201101';
INSERT dbo.calls SELECT 'mfg1','12345','201202';
INSERT dbo.calls SELECT 'mfg2','98765','201202';
Current result set:
mfg part_number last_call
mfg1 12345 201101
mfg3 A1234 NULL
What I want:
mfg part_number last_call
mfg1 12345 201101
mfg2 98765 NULL
mfg3 A1234 NULL
I think it just needs to be:
Why? Because moving an outer join criteria to the where clause converts the outer join to an inner join.