2014-11-25 87 views
3

讓我從數據開始,更好地描述我需要的內容。我有一個名爲超市具有以下字段的表:LISTAGG:組內組

Field 1: StoreID 
Field 2: ProductCategory 
Field 3: ProductID 

的數據將是這樣的:

1, Fruit, Banana 
1, Fruit, PineApple 
1, Fruit, Strawberry 
1, Beverage, Milk 
1, Beverage, Chocolate Milk 
1, Beverage, Apple Juice 
1, Vegetable, beet 
2, Vegetable, beet 
2, Vegetable, onion 
2, Vegetable, Kyle 

,我想有這樣一個觀點:

1, Fruit:(Banana, PineApple, Strawberry), Beverage:(Milk, Chocolate Milk, Apple Juice), Vegetable: (beet) 
2, Vegetable:(beet, onion, kyle) 

Oracle是否有辦法顯示我正在尋找的信息,如上所述?我曾嘗試:

SELECT "StoreID", LISTAGG("ProductCategory",',') WITHIN GROUP (ORDER BY "ProductCategory") "ProductCategories" FROM SUPERMARKET GROUP BY "StoreID" 

但是這一次只列出:

1, "Fruit,Beverage,Vegetable" 
2, "Vegetable" 

,或者如果我使用的產品ID,而不是產品分類然後我得到的產品名單按類別顯示的隨意和不分組

SELECT "StoreID", LISTAGG("ProductID",',') WITHIN GROUP (ORDER BY "ProductID") "Products" FROM SUPERMARKET GROUP BY "StoreID" 

有沒有人有一招如何解決這個問題?請幫忙。

更新併發出帶有VIEW:

的SQL被大家所提出的工作就像一個魅力,直到我試圖把完全相同的工作SQL到視圖。出於某種原因,甲骨文編譯器不喜歡它,並拋出錯誤:

Error(s) parsing SQL: 
Unexpected token near *!* in the following: 
|| ')', ', ') WITHIN *!*GROUP (
Unexpected token near *!* in the following: 
|| ')', ', ') WITHIN GROUP *!*(
Missing expression near *!* in the following: 
|| ')', ', ') WITHIN GROUP (
*!*ORDER BY ProductCategory) AS ProductsAndCategories 

有誰知道這是爲什麼?既然它與我原來的問題有關,我想我會把它放在同一個問題中,以備將來參考。從戈登

enter image description here

建議:

這實際上是從SQL開發GUI的錯誤。繞過問題 - >使用語句創建視圖。

+0

小提琴將是有益的 – Mihai 2014-11-25 14:09:00

+0

使用語句來創建爲我工作的看法。用戶界面的方式沒有工作。 – intA 2017-09-14 08:28:28

回答

4

做聚合兩個層次:

SELECT storeId, 
     LISTAGG(ProductCategory || ':' || '(' || ProductIds || ')', ', ') 
      WITHIN GROUP (ORDER BY ProductCategory) as ProductsAndCategories 
FROM (SELECT StoreId, ProductCategory, 
      LISTAGG(ProductId, ',') WITHIN GROUP (ORDER BY ProductId) as ProductIds 
     FROM SUPERMARKET 
     GROUP BY StoreId, ProductCategory 
    ) s 
GROUP BY StoreId; 
+0

您建議的SQL工作得很完美......直到我將它放入視圖中並且Oracle編譯器生成了奇怪的錯誤。我們不應該把listagg放在視圖中嗎? – user1205746 2014-12-01 21:42:27

+0

@ user1205746。 。 。我剛剛在Oracle中創建,它工作正常。 (我不希望這方面有限制。) – 2014-12-01 21:47:31

+0

好的,戈登。我會再試一次,看看我可能錯過了什麼。我已經多次嘗試過,因爲我沒有聽到你的聲音......嗯.. – user1205746 2014-12-01 22:01:00

1
SELECT storeid, 
    listagg(a,',') within GROUP (
ORDER BY a) 
FROM 
    (SELECT storeid, 
    productCategory 
    ||'(' 
    ||listagg(productId,',') within GROUP (
    ORDER BY productId) 
    ||')' a 
    FROM supermarket 
    GROUP BY storeid, 
    productCategory 
) 
GROUP BY storeid