Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

oracle - SQL - explanation on PIVOT behavior

For the cost column values from a table course, try to pivot into a table of how many times a cost values happens, e.g $1095 happens 3 times.

      1095       1195       1595       NULL
---------- ---------- ---------- ----------
         3         25          1          1

Cost values

select cost from course
order by cost;

COST
----------
1095
1095
1095
1195
...
1195
1595
NULL

This works.

WITH counter AS (
    SELECT 
        cost
    FROM course    
)
select * from counter
pivot (
    count(*)
    for (cost)
    in (1095, 1195, 1595, NULL)
);

      1095       1195       1595       NULL
---------- ---------- ---------- ----------
         3         25          1          1

This does not.

select cost from course
pivot (
    count(*)
    for (cost)
    in (1095, 1195, 1595, NULL)
);

ORA-00904: "COST": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 178 Column: 8

Question

It seems to me both selecting cost and doing count(*) but the former worked but the latter did not. Please help understand why.

question from:https://stackoverflow.com/questions/65870160/sql-explanation-on-pivot-behavior

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • select cost from course doesn't work

    SQL> select cost from course
      2  pivot (
      3      count(*)
      4      for (cost)
      5      in (1095, 1195, 1595, NULL)
      6  );
    select cost from course
           *
    ERROR at line 1:
    ORA-00904: "COST": invalid identifier
    

    See the asterisk? Points to error cause.

  • select * from course works:

    SQL> select * from course
      2  pivot (
      3      count(*)
      4      for (cost)
      5      in (1095, 1195, 1595, NULL)
      6  );
    
          1095       1195       1595       NULL
    ---------- ---------- ---------- ----------
             2          1          1          0
    

Reason? That's the syntax:

SELECT * FROM                  --> here; there's no "COLUMN1" or "<column list>" but "*"
(
  SELECT column1, column2
  FROM tables
  WHERE conditions
)
PIVOT 
(
  aggregate_function(column2)
  FOR column2
  IN ( expr1, expr2, ... expr_n) | subquery
)
ORDER BY expression [ ASC | DESC ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...