用于分隔数字和字符串的SQL查询

时间:2015-03-02 21:07:19

标签: sql-server

我有一个名为duration的列表,其中数据本质上是字母数字。我想将一列分成三列并在其中执行算术。

例如:

    Duration
    30 days
    15day
    0week
    10 week
    1 mo
    7 months 
    QS ys 90days etc.
  • 如果持续时间的值以天为单位,则应乘以1
  • 如果持续时间的值以周为单位,则应乘以7
  • 如果持续时间的值以月为单位,则应乘以30

我试图达到最终结果如下

    Duration      Number     Unit       Final_Duration
    30 days       30         days       30
    15day         15         day        15
    0week         0          week       0
    10 week       10         week       70
    30 days       30         days       30
    1 mo          1          mo         30
    7 months      7          months     210
    QS ys 90days  90         days       90

以下是我的代码,我已经实现了除最后一个数据之外的所有数据" QS是90天"投掷错误。

SELECT DISTINCT
    duration, 
    LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) AS Number,
    LTRIM(RIGHT(duration, LEN(duration) - PATINDEX('%[0-9][^0-9]%', duration ))) As Unit,
    CASE
       WHEN lower(duration) LIKE '%d%' 
         THEN LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 1
       WHEN lower(duration) LIKE '%day%' 
         THEN LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 1
       WHEN lower(duration) LIKE '%dd%' 
         THEN LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 1
       WHEN lower(duration) LIKE '%w%' 
         THEN LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 7
       when lower(duration) like '%week%' 
         then LEFT(duration, PATINDEX('%  [0-9][^0-9]%', duration)) * 7
       when lower(duration) like '%m%' 
         then LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 30
       when lower(duration) like '%month%' 
         then LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 30
       when lower(duration) like '%mth%' 
         then LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 30
       when lower(duration) like '%mm%' 
         then LEFT(duration, PATINDEX('%[0-9][^0-9]%', duration)) * 30
     END AS  Final_Duration 
FROM
    [TEST].[dbo].[Detail]

非常感谢任何帮助。

提前致谢。

0 个答案:

没有答案