Sql LISTAGG:组中的组

Sql LISTAGG:组中的组,sql,oracle,Sql,Oracle,让我从数据开始,更好地描述我需要什么。我有一个名为SUPERMARKET的表,其中包含以下字段: 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,

让我从数据开始,更好地描述我需要什么。我有一个名为SUPERMARKET的表,其中包含以下字段:

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)
我想有这样一个观点:

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"
或者,如果我使用ProductID而不是ProductCategory,那么我会得到一个随机显示的产品列表,而不是按类别分组

SELECT "StoreID", LISTAGG("ProductID",',') WITHIN GROUP (ORDER BY "ProductID") "Products" FROM SUPERMARKET GROUP BY "StoreID"
有人有办法解决这个问题吗?请帮忙

随视图更新和发布:

在我尝试将完全相同的工作sql放入视图之前,每个人都建议的sql非常有效。由于某些原因,Oracle编译器不喜欢它并抛出错误:

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
有人知道为什么吗?由于它与我原来的问题有关,我想我会把它放在同一个问题中,以便将来参考

戈登的建议


这实际上是来自SQLDeveloperGUI的一个bug。要绕过问题->使用语句创建视图。

执行两级聚合:

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;

一把小提琴将有助于使用语句创建适合我的视图。UI方式不起作用。您建议的SQL非常有效。。。直到我把它放到一个视图中,Oracle编译器生成了一个奇怪的错误。我们不应该把listagg放在视野中吗?@user1205746。我刚在Oracle中创建了一个,它运行得很好。(我不认为这会有限制。)好的,戈登。我会再试一次,看看我可能错过了什么。在窃听你之前我已经试过多次了。。。嗯……是的。。这对我来说绝对是个问题。不知道为什么。我用屏幕截图更新了这个问题。奇怪的