【问题标题】:Splitting comma in sql在sql中拆分逗号
【发布时间】:2015-12-19 12:22:19
【问题描述】:

我有一张这样的桌子

select SupplierID,ProductIDs from T_ProductSupplierTable

输出是

SupplierID  ProductIDs
1             1,2,3
2             2,3,4
3             1,5,2

我需要这样的答案

SupplierID  ProductIDs
1           1
1           2
1           3
2           2
2           3
2           4
3           1
3           5
3           2

如何生成查询...?

【问题讨论】:

  • 这将取决于您的 DBMS(Oracle、SQL Server、MySQL...)

标签: sql sql-server-2008 split


【解决方案1】:

假设您有一个产品 ID 表,有一种方法可以使用 ANSI 标准 SQL 来执行此操作,该方法可以在几个数据库中工作(并且接近于在更多数据库中工作):

select s.SupplierId, p.ProductId
from T_ProductSupplierTable s join
     Products p
     on concat(',', s.productIds, ',') like concat('%,', p.ProductId, ',%');

(数据库之间的差异在于 concat() 函数。)

无论如何,我实际上并不推荐这种方法,因为大多数数据库都有其他可能更快的方法。

编辑:

在 SQL Server 中:

select s.SupplierId, p.ProductId
from T_ProductSupplierTable s join
     Products p
     on ',' + s.productIds + ',') like '%,' + cast(p.ProductId as varchar(255)) + ',%';

【讨论】:

  • 我正在使用 sql server 2008... concat 函数不起作用
【解决方案2】:

您可以使用 Internet 上的一些现成函数来拆分您的字符串并转换为稍后您可以加入到 SubpplierID 的表格。

另一个不使用函数的选项在这里Sample in SQL Fiddle

SELECT supplierid,
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS ProductIDs 
FROM
(
SELECT supplierid,CAST('<XMLRoot><RowData>' + REPLACE(ProductIDs ,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM   tab
)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)

【讨论】:

    【解决方案3】:

    您也可以为此使用递归 cte。 Sample

    with cte as (
      select SupplierID, ProductIDs as IDs, cast(null as varchar(8000)) as Product, charindex(',',ProductIDs) as nxt
      from tab
      union all
      select SupplierID, substring(IDs,nxt+1,8000), left(IDs,nxt-1), charindex(',',IDs,nxt+1)-nxt
      from cte where nxt > 0
      union all
      select SupplierID, null, IDs, null
      from cte where nxt <= 0
    )
    select supplierid, Product from cte where Product is not null
    

    【讨论】:

      猜你喜欢
      • 2013-10-05
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2014-06-17
      • 2018-12-25
      • 2015-04-01
      相关资源
      最近更新 更多