简体   繁体   中英

SQL values from one column to multiple columns

I'm having trouble joining two tables.

I have this table:

order   line    value
----------------------
12033   hours   0,1
12033   desc    foo
12033   letter  A
12034   hours   0,3
12034   desc    bar
12034   letter  C

Now I want to join the column "value" with another table that only has the unique order numbers in it, and the values in column "line" should become the column headers.

Here's how I want the result to be:

order   hours   desc   letter
-----------------------------
12033   0,1     foo    A
12034   0,3     bar    C

Could someone give me some tips on how to achieve this?

Thanks!

You could use a self-join. Something like this might work.

SELECT      a.order_number, b hours, c description, d.letter
FROM        datatable a
LEFT JOIN
(
    SELECT      order_number, value hours
    FROM        datatable
    WHERE       line = 'hours'
) b
ON b.order_number = a.order_number
LEFT JOIN
(
    SELECT      order_number, value description
    FROM        datatable
    WHERE       line = 'desc'
) c
ON c.order_number = a.order_number
LEFT JOIN
(
    SELECT      order_number, value letter
    FROM        datatable
    WHERE       line = 'letter'
) d
ON d.order_number = a.order_number

If you really need to join to another table, you can use this as a subquery.

I recommending not using words like ORDER and DESC as column names, as database engines can get confused if you use reserved words as column names without quoting/escaping them properly.

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