oracle 在以下情况下如何有条件地应用PIVOT

gfttwv5a  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(164)

我有下面的表,并试图PIVOT父和子作为列标题。在我的情况下“作者和书籍”。我能够枢轴要么作者或书籍在一个时间,但不能得到两个在一个时间作为逗号分隔的条件(条件解释如下)。我已经给出了样本数据和output.author1和作者2列显示“平均”的评论沿着颜色。
r=红色,y=黄色
在示例输出中,我们可以看到color as r & y。我在这里应用了一个条件。如果一个作者在任何时候得到“r”,那么输出总是“r”,否则是“y”。在我的第一个例子中,author1得到y & r。所以输出是r。其他情况下“r”没有得到,所以显示“y”。如果没有分配颜色,它应该是“NA”。

user
Aid userName
1   author1
2   author2

books
bid NAME Aid
1    x    1
2    y    1
3    z    2

Location
loc_id Loc_name

1     UK
2     USA
3     Europe

UserAssign

uid Aid bid loc_d color reviews
1    1   1   1     y    12
2    1   2   1     r    14
3    2   3   1     y    11
4    1   1   2     y    10
5    2   3   2     y    112

Expected o/p
--------------------------------------------

Location  author1   x  y  author2       z
Uk        r,13     12 14  y,11         11
USA       y,10     10     y,112       112
e0bqpujr

e0bqpujr1#

无法以您要求的格式进行有用的查询。当使用PIVOT时,结果中预期的栏数应该永远相同。在您显示数据的格式中,如果有新书或新作者,则会新增额外的栏。
下面的查询仅适用于指定的帐套和作者:

WITH
    users (aid, username)
    AS
        (SELECT 1, 'author1' FROM DUAL
         UNION ALL
         SELECT 2, 'author2' FROM DUAL),
    books (bid, name, aid)
    AS
        (SELECT 1, 'x', 1 FROM DUAL
         UNION ALL
         SELECT 2, 'y', 1 FROM DUAL
         UNION ALL
         SELECT 3, 'z', 2 FROM DUAL),
    location (loc_id, loc_name)
    AS
        (SELECT 1, 'UK' FROM DUAL
         UNION ALL
         SELECT 2, 'USA' FROM DUAL
         UNION ALL
         SELECT 3, 'Europe' FROM DUAL),
    UserAssign (u_UID,
                Aid,
                bid,
                loc_id,
                color,
                reviews)
    AS
        (SELECT 1, 1, 1, 1, 'y', 12 FROM DUAL
         UNION ALL
         SELECT 2, 1, 2, 1, 'r', 14 FROM DUAL
         UNION ALL
         SELECT 3, 2, 3, 1, 'y', 11 FROM DUAL
         UNION ALL
         SELECT 4, 1, 1, 2, 'y', 10 FROM DUAL
         UNION ALL
         SELECT 5, 2, 3, 2, 'y', 112 FROM DUAL)
SELECT l.loc_name, p.*
  FROM (  --authors
          SELECT loc_id,
                 u.username                                  AS colheader,
                 MIN (color) || ',' || AVG (ua1.reviews)     AS avg_reviews
            FROM userassign ua1 JOIN users u ON (ua1.aid = u.aid)
        GROUP BY loc_id, u.username
        UNION ALL
        --books
        SELECT loc_id, b.name, TO_CHAR (ua2.reviews) AS avg_reviews
          FROM userassign ua2 JOIN books b ON (ua2.bid = b.bid))
       PIVOT (MIN (avg_reviews)
             FOR colheader
             IN ('author1' AS author1,
                'x' AS x,
                'y' AS y,
                'author2' AS author2,
                'z' AS z)) p
       JOIN location l ON (p.loc_id = l.loc_id)
ORDER BY l.loc_name;

LOC_NAME       LOC_ID AUTHOR1    X     Y     AUTHOR2    Z
___________ _________ __________ _____ _____ __________ ______
UK                  1 r,13       12    14    y,11       11
USA                 2 y,10       10          y,112      112

相关问题