仅返回t-sql中列的数值

时间:2015-04-02 08:54:08

标签: sql-server tsql sql-server-2008-r2

我要求比较两个记录: 我的桌子就像;

EmpNo payband              ContractType
123   band 4               permanent
124   band 4               contract
125   band 3               permanent
125   band 4               permanent
125   band 5 reviewbody    permanent

现在我想过滤重复的记录,我的第一个条件是ContractType =' permanent'然后通过高频段过滤。在上面的表中,EmpNo 125是一个雇员和同一个合同类型我希望通过高支付率过滤他的记录。在payband column

中弄得一团糟

我想输出像:

EmpNo payband   ContractType
123   band 4    permanent
125   band 5    permanent

任何帮助?感谢

1 个答案:

答案 0 :(得分:0)

我添加了逻辑,如果没有数值,那么任何第一个波段都会出现在输出中:

DECLARE @t TABLE
    (
      EmpNo INT ,
      payband NVARCHAR(MAX) ,
      ContractType NVARCHAR(MAX)
    )

INSERT  INTO @t
VALUES  ( 123, 'band 4', 'permanent' ),
        ( 124, 'band 4', 'contract' ),
        ( 125, 'band 3', 'permanent' ),
        ( 125, 'band 4 review body', 'permanent' ),
        ( 128, 'band', 'permanent' );

WITH    cte1
          AS ( SELECT   EmpNo ,
                        payband ,
                        ContractType ,
                        PATINDEX('%[0-9]%', payband) AS pi ,
                        CHARINDEX(' ', payband, PATINDEX('%[0-9]%', payband)) AS ci
               FROM     @t
               WHERE    ContractType = 'permanent'
             ),
        cte2
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( PARTITION BY EmpNo ORDER BY CASE
                                                              WHEN pi > 0
                                                              THEN CAST(SUBSTRING(payband,
                                                              pi, ABS(pi - ci)) AS INT)
                                                              ELSE 0
                                                              END DESC ) AS rn
               FROM     cte1
             )
    SELECT  EmpNo ,
            payband ,
            ContractType
    FROM    cte2
    WHERE   rn = 1

输出:

EmpNo   payband             ContractType
123     band 4              permanent
125     band 4 review body  permanent
128     band                permanent