Turn values from table into column headers

吃可爱长大的小学妹 提交于 2020-01-17 05:38:30

问题


I'm trying to take values from rows of a table and turn them into column headers. For example, my table currently looks like this:

 _id   question_id   category
----- ------------- ----------
  1    767           back
  1    768           dev
  2    768           dev

and I would like it to look like this:

 _id   767      768
----- -------- -----
  1    back     dev
  2    (null)   dev

I have found solutions on here using CASE/WHEN, but I am getting errors when trying to implement the solutions. My code is below. In this case, I am getting a ORA-00923: FROM keyword not found where expected error at the end of line 6. How can I fix this?

SELECT
 msr._id,
 ans.question_id,
 ans.category,

 CASE ans.question_id WHEN '767' THEN ans.category END '767',
 CASE ans.question_id WHEN '768' THEN ans.category END '768'

FROM table1 t1
LEFT OUTER JOIN table2 t2
ON t1._id = t2._id

WHERE t2.question_id in (767,768) AND t2.assigned_to not in ('Smith, John')
 AND t1.request_type_id in (288,289) and t1.status_id not in (0, 11);

回答1:


' is the delimiter for string literals. " is for column names. Hence:

 CASE ans.question_id WHEN '767' THEN ans.category END "767",
 CASE ans.question_id WHEN '768' THEN ans.category END "768"


来源:https://stackoverflow.com/questions/32119268/turn-values-from-table-into-column-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!