sql縱錶轉橫表

縱表product_attribute

product_id    attribute_name  attribute_value

1                   book_name          數據結構

1                    price                    20.1

1                   publication_date  2011-01-04

2                   book_name          C語言程序設計

2                   price                     30.1

2                   publication_date  2011-02-16

 

橫表

book_id       book_name         price   publication_date

1                    數據結構              20.1    2011-01-04

2                     C語言程序設計     30.1    2011-02-16

 

sql:

select productid as book_id,

    max(case attribute_name
        when 'book_name' then
            value
        else
            0
        end) as book_name,
   max(case attribute_name
        when 'price' then
            value
        else
            0
        end) as price,
   max(case attribute_name
        when 'publication_date' then
            value
        else
            0
        end) as publication_date
    from product_attribute group by book_id;

 

如果是數字:max可以用sum代替


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章