2012-08-15 77 views
2

我對此主題有兩個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

關於StackOverflow的問題只能有一個「最好」或「接受」的答案。這一個可能會有兩個,因爲一個人將發佈正確答案的可能性很小。我強烈建議爲Oracle問題提出一個單獨的問題。 – 2012-08-15 14:23:18

回答

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的版本,但我要猜測如果用空字符串排除值,逗號將消失。

+0

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