USE Tempdb
GO
CREATE TABLE SKUTable (
ID int
,SKU varchar(30)
,SIZE VARCHAR(255)
)
GO
INSERT INTO SKUTable
VALUES
(61, 'AL01', '1.6x1.6')
,(60, 'AL01', '10''RD')
,(62, 'AL01', '10x14')
,(63, 'AL01', '12x15')
,(64, 'AL01', '2x3')
,(65, 'AL01', '4x6')
,(66, 'AL01', '6x9')
,(67, 'AL01', '8x10')
,(68, 'AL01', '9x12')
,(83, 'AL03', '10x14')
,(84, 'AL03', '10''RD')
,(85, 'AL03', '2x3')
,(86, 'AL03', '4x6')
,(87, 'AL03', '6x9')
,(88, 'AL03', '8x10')
GO
DECLARE @Separator char(1) = 'X'
,@MaxSize NUMERIC(20,4) = 9999.999
;with CalculateSize as (
SELECT
*
,RealSize = (
CASE WHEN CHARINDEX(@Separator,Size) = 0 THEN @MaxSize
ELSE CAST(LEFT(Size,CHARINDEX(@Separator,Size)-1) as NUMERIC(20,4)) END
*
CASE CHARINDEX(@Separator,Size) WHEN 0 THEN @MaxSize
WHEN LEN(Size) THEN @MaxSize
ELSE CAST(SUBSTRING(Size,CHARINDEX(@Separator,Size)+1,8000) as NUMERIC(20,4)) END)
FROM SKUTable
)
, OrderBySize as (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SKU ORDER BY (RealSize)) as OrderNum
FROM CalculateSize
)
SELECT *
FROM OrderBySize
WHERE OrderNum = 1 -- WHERE OrderNum < 5
GO
DROP TABLE SKUTable
GO