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
485 views
in Technique[技术] by (71.8m points)

oracle11g - Oracle Pivot - converting values into columns

I have table in Oracle 11g with 3 fields:

 STUDYID  |  STUDY_PARAMETER  | STUDY_VALUE

  5268    |  Age Group        | ADULT (18-65)
  5269    |  Age Group        | ADULT (18-65)
  5270    |  Age Group        | ADULT (18-65)
  5271    |  Age Unit         | ADULT (18-65)    
  1668A   |  Trial Type       | ADULT (18-65)
  5273    |  Trial Type       | Dispensing
  5345    |  Age Unit         | Years
  1668AC  |  Age Group        | ADULTS (18-39)

So, what I need is to display values in this order:

STUDY_ID  |  AGE_GROUP     |  AGE_UNIT |  TRIAL_TYPE

  5268    |  ADULT (18-65) |  Years    | Dispensing
  5269    |  ADULT (18-65) |  (null)   | (null)
  1668AC  |  ADULTS (18-39)|  Years    | Non - Dispensing

and so on.

What I have so far is:

SELECT *
FROM  (
        SELECT STUDYID, STUDY_VALUE, STUDY_PARAMETER
        FROM   RD.STUDY_INFO
      )
PIVOT (
        SUM(STUDY_VALUE)
        FOR (STUDY_PARAMETER) 
        IN (
              'Age Unit' AS AGE_UNIT,
              'Age Group' AS AGE_GROUP,
              'Trial Type' AS TRIAL_TYPE
           )
      );

I learned this from examples on the net but I am not sure if I can use SUM() like this...?!

I get this error:

ORA-01722: invalid number
01722. 00000 -  "invalid number"

Does anyone see what I am doing wrong?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Since the STUDY_VALUE column appears to be a string, you will need to use either the max() or min() aggregate function on the values:

SELECT *
FROM  
(
  SELECT STUDYID, STUDY_VALUE, STUDY_PARAMETER
  FROM   STUDY_INFO
)
PIVOT 
(
  MAX(STUDY_VALUE)
  FOR (STUDY_PARAMETER) IN ('Age Unit' AS AGE_UNIT,
                              'Age Group' AS AGE_GROUP,
                              'Trial Type' AS TRIAL_TYPE)
);

See SQL Fiddle with Demo


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

...