1

我有一个如下表:

ID   SKU   SIZE
------------------
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

在这里,尺寸被分组为 SKU。意味着 SKU 可以有多种尺寸。我想选择具有最小尺寸的 SKU 的最小 ID。例如,对于 SKU='AL03' 它应该返回 ID=85 且最小尺寸='2x3'

4

1 回答 1

0
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
于 2013-11-07T10:36:17.880 回答