SQL Server和ORACLE中的STUFF函数

时间:2012-08-15 13:58:47

标签: sql-server oracle8i

我对此主题有两个STUFF个问题。

第一个问题是SQL Server中的STUFF函数。第二个问题是关于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(删除逗号(,)。

1 个答案:

答案 0 :(得分:3)

问题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版本,但我猜测如果用空字符串排除值,则逗号将消失。