STUFF函数在SQL Server和ORACLE中

问题描述:

我对此主题有两个STUFF问题。STUFF函数在SQL Server和ORACLE中

第一个问题是STUFF函数在SQL Server中。第二个问题是关于Oracle(8i)中的STUFF函数。

问题1:如何从列中删除,我想要的东西?

例如,假设表:

ID  Country  Payment  Product 
12345  USA  Cash  Red wine 
12345  USA  Cash  
12345  USA  Cash 

使用这个脚本,它产生:

select distinct Country, Payment, 
stuff(isnull((select ', ' + x.Product from #temp x where x.ID = t.ID 
group by x.Product for xml path ('')), ''), 1, 2, '') as Product 


ID  Country  Payment  Product 
12345 USA   Cash  , Red wine 

如何删除结果只显示Red wine只(删除逗号(,)

请注意:我没有写这个STUFF函数,它是由一个名叫OMG Ponies的人写的

问题2:同问题1,但语法是Oracle:

select distinct ID, Country, Payment, WM_CONCAT(Product) AS Products 
from 
(
select distinct ID, Country, Payment, Product 
from temp table 
)x 
group by ID, Country, Payment 

我想我的结果只显示Red wine只(删除逗号(,)。

+2

这在我看来应该是两个不同的问题。 – 2012-08-15 14:16:05

+0

是的,这是两个单独的问题,如上所述 – joe 2012-08-15 14:21:28

+1

关于*的问题只能有一个“最好”或“接受”的答案。这一个可能会有两个,因为一个人将发布正确答案的可能性很小。我强烈建议为Oracle问题提出一个单独的问题。 – 2012-08-15 14:23:18

问题1: 至于答案的SQL Server的一部分,它看起来像你有空字符串在你的产品领域 - 他们不是空,如果没有一个。所以你可以使用以下。我增加了行and (product != '' and product is not null)Stuff()的一部分,它会删除多余的逗号:

select distinct Country, Payment, 
    stuff(isnull((select ', ' + x.Product 
        from test x 
        where x.ID = t.ID 
         and (product != '' and product is not null) 
        group by x.Product for xml path ('')), ''), 1, 2, '') as Product 
from test t 

SQL Fiddle with Demo

问题2:我没有访问Oracle 8i的版本,但我要猜测如果用空字符串排除值,逗号将消失。

+0

谢谢bluefeet!我只是测试它。它完美的工作!再次感谢。 – joe 2012-08-15 14:57:43