Oracle 10g 中的透视/交叉表查询(动态列号)

发布于 2024-09-14 10:09:16 字数 571 浏览 6 评论 0原文

我有这个表视图

UserName      Product     NumberPurchaces
--------      -------     ---------------
'John Doe'    'Chair'     4
'John Doe'    'Table'     1
'Jane Doe'    'Table'     2
'Jane Doe'    'Bed'       1

如何创建在 Oracle 10g 中提供此数据透视表的查询?

 UserName   Chair   Table   Bed
 --------   -----   -----   ---
 John Doe   4       1       0
 Jane Doe   0       2       1

有什么办法动态地做到这一点吗?我看到了很多方法(解码、PL/SQL 循环、联合、11g 枢轴),

但我还没有根据上面的示例找到适合我的方法


编辑:我不知道开发期间产品的数量或类型,因此必须是动态的

I have this table view

UserName      Product     NumberPurchaces
--------      -------     ---------------
'John Doe'    'Chair'     4
'John Doe'    'Table'     1
'Jane Doe'    'Table'     2
'Jane Doe'    'Bed'       1

How can I create a query that will provide this pivot view in Oracle 10g ?

 UserName   Chair   Table   Bed
 --------   -----   -----   ---
 John Doe   4       1       0
 Jane Doe   0       2       1

Any way to do it dynamically? I saw so many approaches (decode, PL/SQL loops, unions, 11g pivot)

But I've yet to find something that will work for me based on the above example


Edit: I don't know the number or type of products in development time so this has to be dynamic

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜夜流光相皎洁 2024-09-21 10:09:16

Oracle 11g 是第一个支持PIVOT/UNPIVOT 的,所以你必须使用:

  SELECT t.username,
         MAX(CASE WHEN t.product = 'Chair' THEN t.numberpurchases ELSE NULL END) AS chair,
         MAX(CASE WHEN t.product = 'Table' THEN t.numberpurchases ELSE NULL END) AS tbl,
         MAX(CASE WHEN t.product = 'Bed' THEN t.numberpurchases ELSE NULL END) AS bed
    FROM TABLE t
GROUP BY t.username

可以使用DECODE,但是从9i 开始就支持CASE。

Oracle 11g is the first to support PIVOT/UNPIVOT, so you have to use:

  SELECT t.username,
         MAX(CASE WHEN t.product = 'Chair' THEN t.numberpurchases ELSE NULL END) AS chair,
         MAX(CASE WHEN t.product = 'Table' THEN t.numberpurchases ELSE NULL END) AS tbl,
         MAX(CASE WHEN t.product = 'Bed' THEN t.numberpurchases ELSE NULL END) AS bed
    FROM TABLE t
GROUP BY t.username

You could use DECODE, but CASE has been supported since 9i.

度的依靠╰つ 2024-09-21 10:09:16

我想人们必须编写一些代码来动态创建查询。除了“CHAIR”、“TABLE”等字符串之外,每个 MAX() 行都是相同的。

因此,人们必须遍历数据才能找到所有产品并构建第二个查询。然后执行动态构建的查询。

I guess one would have to write some code to dynamically create the query. Each MAX() line is identical except for the 'CHAIR', 'TABLE', etc, strings.

So, one would have to itterate through the data to find all the products and build up a second query as one goes. Then execute that dynamically built query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文