mysql 行轉換列

來源:互聯網
上載者:User

標籤:blog   http   io   ar   使用   sp   for   on   資料   

http://www.cnblogs.com/acelove/archive/2004/11/29/70434.html上提到了一個行列轉換的方法,其實在2005裡有更可讀的寫法,就是使用pivot運算子:

create table abc 
(
student varchar(50),
class varchar(50),
grade int
)
INSERT INTO abc
SELECT ‘孫小美‘,‘數學‘,10 UNION ALL
SELECT ‘孫小美‘,‘語文‘,20 UNION ALL
SELECT ‘孫小美‘,‘英語‘,30 UNION ALL
SELECT ‘阿土伯‘,‘數學‘,40 UNION ALL
SELECT ‘阿土伯‘,‘語文‘,50 UNION ALL
SELECT ‘阿土伯‘,‘英語‘,60 UNION ALL
SELECT ‘小叮鐺‘,‘數學‘,70 UNION ALL
SELECT ‘小叮鐺‘,‘語文‘,80 UNION ALL
SELECT ‘小叮鐺‘,‘英語‘,90

SELECT 
    student,
    MAX(數學) AS 數學,
    MAX(語文) AS 語文,
    MAX(英語) AS 英語
FROM
    (
    SELECT 
        student,
        CASE class WHEN ‘數學‘ THEN grade END AS 數學,
        CASE class WHEN ‘語文‘ THEN grade END AS 語文,
        CASE class WHEN ‘英語‘ THEN grade END AS 英語
    FROM abc
    ) AS a
GROUP BY student 
--用pivot運算子
select student,[數學] as ‘數學‘,[語文] as ‘語文‘ ,[英語] as ‘英語‘
from
 (select * from abc) as source
    pivot
    (
        sum(grade)
        for class  in
        ([數學],[語文],[英語])
    ) as p


不過對於不知道具體列名的程式還真不好解決,產生動態sql話(調用sp_executesql),臂如:

declare @sql varchar(8000)
set @sql = ‘select student,‘
select @sql = @sql + ‘sum(case class when ‘‘‘+class+‘‘‘then grade else 0 end) as ‘‘‘+class+‘‘‘,‘
  from (select distinct class from abc) as a 
select @sql = left(@sql,len(@sql)-1) + ‘ from abc group by student‘
exec(@sql)

倒是可以,不過卻與當前預存程序調用不屬於一批命令了,定義的CTE,局部暫存資料表也訪問不了,似乎只有放到業務層或資料層去解決了.

mysql 行轉換列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.