Jes Sie

Jes Sie

  • 704
  • 1.2k
  • 265.1k

How to get the Min and Max in SQL SERVER

Aug 20 2019 2:12 AM
Below is my table in SQL SERVER. What I want is to extract the lowest partsCost and the latest partsCost inserted into the table:
 
Below is my stored procedure but does not work:
  1. ALTER PROCEDURE [dbo].[spClaims_GetLowestLatestPrice] --'honda','civic','1'  
  2.     -- Add the parameters for the stored procedure here  
  3.      @carMake nvarchar(50),  
  4.      @carModel nvarchar(50),  
  5.      @partsCode int  
  6. AS  
  7. BEGIN  
  8.     -- SET NOCOUNT ON added to prevent extra result sets from  
  9.     -- interfering with SELECT statements.  
  10.     SET NOCOUNT ON;  
  11.   
  12.     -- Insert statements for procedure here  
  13.   
  14.     with query1 as  
  15.     (SELECT ISNULL(partsCost,0) AS LowestPrice  
  16.     FROM claimsPartsMasterList   
  17.     WHERE carMake = @carMake AND carModel = @carModel AND partsCode = @partsCode AND partsCost = (SELECT MIN(partsCost) FROM claimsPartsMasterList AS LowestPrice)),  
  18.       
  19.     query2 as  
  20.     (SELECT ISNULL(partsCost,0) AS LatestPricePurchase  
  21.     FROM claimsPartsMasterList    
  22.     where carMake = @carMake AND carModel = @carModel AND partsCode = @partsCode AND getLogs = (SELECT MAX(getLogs) FROM claimsPartsMasterList AS LatestPricePurchase))  
  23.   
  24.     SELECT LowestPrice, LatestPricePurchase from query1, query2  
  25.   
  26. END  
 
 
Hope someone can help with this. Thanks in advance. 
 

Answers (4)