T-SQL如何将多个子字符串转换为新值

时间:2013-07-11 02:24:38

标签: sql sql-server tsql

首先,抱歉,因为我不知道如何解决我的问题。

我的情况是,我有一个这种格式的查找表:

+----+-----------+------------+
| ID | Fruit     |  Color     |
+----+-----------+------------+
|  1 | Banana    | Yellow     |
|  2 | Apple     | Red        |
|  3 | Blueberry | NotYetBlue |
+----+-----------+------------+

我的主表是这样的:

+-------+------------------------+------------+
| MixID |        Contains        | MixedColor |
+-------+------------------------+------------+
|     1 | Banana                 |            |
|     2 | Apple:Blueberry        |            |
|     3 | Banana:Apple:Blueberry |            |
+-------+------------------------+------------+

我想在第一个表格上查找并填写下面的MixedColor列:

+-------+------------------------+-----------------------+
| MixID |        Contains        |      MixedColor       |
+-------+------------------------+-----------------------+
|     1 | Banana                 | Yellow                |
|     2 | Apple:Blueberry        | Red:NotYetBlue        |
|     3 | Banana:Apple:Blueberry | Yellow:Red:NotYetBlue |
+-------+------------------------+-----------------------+

非常感谢任何帮助。

谢谢

2 个答案:

答案 0 :(得分:3)

正如“查尔斯布雷塔纳”所建议的那样,最好将模式修改为:

+--------+-------+----------+
| RowID  | MixID |  FruitID |
+--------+-------+----------+
|    0   |     1 |     1    | 
|    1   |     2 |     2    | 
|    2   |     2 |     3    | 
|    3   |     3 |     1    | 
|    4   |     3 |     2    | 
|    5   |     3 |     3    | 
|--------+-------+----------+

现在使用简单的inenr join,您可以选择正确的颜色并匹配水果。

如果您无法实现该构造,则可以使用此处提到的递归查询:Turning a Comma Separated string into individual rows。 操纵你的数据看起来像那样。

这是一个SQL小提琴:http://sqlfiddle.com/#!3/8d68f/12

表数据:

create table Mixses(MixID int, ContainsData varchar(max))
insert Mixses select 1,  '10:11:12'
insert Mixses select 2,  '10:11'
insert Mixses select 3,  '10'
insert Mixses select 4,  '11:12'

create table Fruits(FruitID int, Name varchar(200), Color varchar(200))
insert Fruits select 10,  'Bannana'    , 'Yellow'
insert Fruits select 11,  'Apple'      , 'Red'
insert Fruits select 12,  'BlueBerry'  , 'Blue'
insert Fruits select 13,  'Pineapple'  , 'Brown'

查询:

;with tmp(MixID, DataItem, Data)  as 
(
  select 
        MixID, 
        LEFT(ContainsData, CHARINDEX(':',ContainsData+':')-1),
        STUFF(ContainsData, 1, CHARINDEX(':',ContainsData+':'), '')
  from Mixses

  union all

  select MixID, 
        LEFT(Data, CHARINDEX(':',Data+':')-1),
        STUFF(Data, 1, CHARINDEX(':',Data+':'), '')
  from tmp
  where Data > ''
)

select t.MixID, t.DataItem, f.Color
from         tmp t
inner join   Fruits f on f.FruitID=t.DataItem
order by MixID

答案 1 :(得分:3)

我同意理想情况下应更改您的表结构。但是,你可以得到你想要的东西:

SELECT   MIXID, [CONTAINS],
STUFF((
          SELECT ':' + Color
          FROM Table1 a
          WHERE ':'+b.[Contains]+':' LIKE '%:'+a.Fruit+':%'
                FOR XML PATH('')
            ), 1, 1, '') AS Color
FROM Table2 b
GROUP BY MIXID, [CONTAINS]

演示:SQL Fiddle