简体   繁体   中英

How to get values from one column and convert it into two columns SQL

I have a SQL Tabel which contains 3 columns (id, size, grade, unit_price) as shown in this picture 1 :

SQL 表图像

I want to display this table in HTML in the form of:

size | grade 40 price | grade 60 price

as shown in the below image:

需要html表格

Do you just want conditional aggregation?

select size,
       max(case when grade = '40 Grade' then unit_price end) as price_40,
       max(case when grade = '60 Grade' then unit_price end) as price_60
from t
group by size;
  1. Your database should be normalized.
  2. For example, you should have at least a product_id to know, to which exactly product, the information refers to. In this case. The only thing that refers the same product - is the same size, which is string, and which is not a good practice.

Here is a code that should work for your case, but I recommend to change your DB schema

SELECT
    p1.size,
    p1.unit_price AS price_grade_40,
    p2.unit_price AS price_grade_60

FROM products AS p1

LEFT JOIN products AS p2
       ON p1.size = p2.size
      AND p2.grade = 'Grade 60'

WHERE p1.grade = 'Grade 40'

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