简体   繁体   中英

How can I pull data from specific rows via SQL and separate them into their own columns?

I apologize if I cannot explain this properly in advance but I will do my best.

I have a SQL table. In the table, there are multiple columns. One of which is labeled 'meta_key' and another which is 'meta_value'. I would like to know how to write SQL that will pull specific rows in one column and also gather the data from another column in the same row and separate all of these out into their own columns. (Please forgive me if this doesn't make sense.)

I've tried the following which was provided by a friend:

SELECT meta_key, meta_value
FROM wp_gf_entry_meta
WHERE meta_key = 3 OR meta_key = 9 OR meta_key = 22 OR meta_key = 23 

But it only gets me halfway there in that it provides all of the data from those rows and columns and consolidates it all into a single column.

Again, the SQL that was tried was:

SELECT meta_key, meta_value
FROM wp_gf_entry_meta
WHERE meta_key = 3 OR meta_key = 9 OR meta_key = 22 OR meta_key = 23 

I didn't receive error messages for above but it did not provide the desired outcome.

Here is a screenshot of the table before the above SQL:

这是上述SQL之前的表格的屏幕截图:

和之后

And here is a screenshot after:

UPDATE

I've made some progress. I believe what they call an 'Aggregate Function' is what I can use.

This has gotten me closer to my goal:

  SELECT 
  max(case when meta_key = 3 then meta_value end) Ticker,
  max(case when meta_key = 9 then meta_value end) Reason,
  max(case when meta_key = 22 then meta_value end) Resistance,
  max(case when meta_key = 23 then meta_value end) Support
  from wp_gf_entry_meta

The only problem now is that it only returns one row and I'm not certain how to make it return more than one row.

Try this:

SELECT meta_key, meta_value
FROM wp_gf_entry_meta
WHERE meta_key IN(3, 9, 22,23)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM