Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

SELECT data from preceding row of result set when the current row has a NULL

$
0
0

The query below produces a result set with two rows of data.  One row of data has nulls for User_Number and User_Name.  The other row has this info.  I need to grab the User_Number and User_Name from the preceding row and incorporate it into the row where it is missing.  I am getting the data from a flattened OLTP database developed by a third party.  I know that DateFrom and DateTo would not normally be Integers but that is what the vendor did and I have to live with it. 

I have provided some sample data.  What I need is to have one line that shows the  data for the event labeled "Stay" but include the User_Number and User_Name captured in the first row.

DECLARE @DateFrom INT
DECLARE @DateTo INT
SET @DateFrom = 20130401
SET @DateTo = 20130430
SELECT CASE  --Finds the abnormnally formatted Dealer_IDs of format XYZ-##R##D### and parses them
		WHEN SUBSTRING(DT.Dealer_ID, 3,1) = '-' THEN SUBSTRING(DT.Dealer_ID, 5, 1)
		--parses the "regularly formatted"  DealerIDs like XY-Z#R##D### 
		ELSE SUBSTRING(DT.Dealer_ID, 4, 2) 
		END AS Div
, SUBSTRING(DT.Dealer_ID, 7,2) AS Reg
, SUBSTRING(DT.Dealer_ID, 10, 3) AS Dist
, SUBSTRING(CU.Customer_ID, 3,5) AS StoreNo
, D.Date_Text + '  ' +T.Time_Text_12_Hour AS [Date Time]
, CA.User_Number
, CA.[User_Name]
, CASE CA.Original_Event_Code
	WHEN '#R441' THEN 'Stay'
	ELSE CA.Original_Event_Code
	END AS ArmingMode

FROM CustomerActivity CA 
INNER JOIN Customers CU ON CU.Customer_Key = CA.Customer_Key
INNER JOIN Dates D ON D.Date_Key = CA.Event_Date_Key
INNER JOIN Times T on T.Time_Key = CA.Event_Time_Key
INNER JOIN DealerTree('XYZ Dealer',1,1) AS DT ON DT.Dealer_ID = CU.Dealer_ID

WHERE d.Date_Key BETWEEN @DateFrom and @DateTo 

AND CU.Customer_ID = 'Store1'
AND CA.Original_Event_Code IN('#R441', '#R401')

ORDER BY D.Date_Text, t.Time_Text_12_Hour


Lee Markum



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>