I have a table called tblAssetsInUse with the following structure:
intPK intAssetID datCheckedOut datCheckedIn 1 450 1/5/2009 10/5/2009 2 300 2/5/2009 <NULL> 3 200 2/5/2009 <NULL> 4 450 12/5/2009 5/7/2009
and I have a SP that receives a scanned Asset ID then either Inserts, or Updates to the table for assets being checked Out or In respectively. As you can see datCheckedIn may be Null which is used to work out which assets are currently in use. This procedure works perfectly. I wish to be able to determine what the last asset to be scanned was and also what the last operation to the table was (i.e. Check In or Out). I have some SQL code which finds the row with the most recent date (regardless of which column) and I then use this to join to a separate Assets View, which also works. I just need to be able to work out if the most recent date was in the Checked Out or Checked In column somehow.
SELECT TOP (1) allDates.intPK, MAX(allDates.datLastAction) AS datLastScan, dbo.viwAssets.strFriendlyName, tblAssetsInUse_join.intAssetID FROM (SELECT intPK, MAX(datCheckedOut) AS datLastAction FROM dbo.tblAssetsInUse AS tblAssetsInUse_out GROUP BY intPK UNION ALL SELECT intPK, MAX(datCheckedIn) AS datLastAction FROM dbo.tblAssetsInUse AS tblAssetsInUse_in GROUP BY intPK) AS allDates INNER JOIN dbo.tblAssetsInUse AS tblAssetsInUse_join ON allDates.intPK = tblAssetsInUse_join.intPK INNER JOIN dbo.viwAssets ON tblAssetsInUse_join.intAssetID = dbo.viwAssets.intPK GROUP BY allDates.intPK, dbo.viwAssets.strFriendlyName, tblAssetsInUse_join.intAssetID ORDER BY datLastScan DESC
Is there a literal value of some kind I can add in so that it flags a bit value in the results perhaps?
Thanks for your help,
Paul Reynolds
Beside from getting the type of operation performed, I think that the whole query could be simplified (and optimized) this way:
EDIT: also note that by removing the TOP 1 in the first line you get both the last Asset checked in and the last checked out.