在MySQL中,如果需要將行數(shù)據(jù)轉(zhuǎn)換為列數(shù)據(jù)進(jìn)行查詢,可以使用PIVOT函數(shù)或自聯(lián)結(jié)查詢語(yǔ)句來(lái)實(shí)現(xiàn)。下面分別介紹一下兩種方法的具體實(shí)現(xiàn)。
-- PIVOT函數(shù)實(shí)現(xiàn): SELECT COALESCE(SUM(CASE WHEN type='A' THEN num END), 0) AS num_A, COALESCE(SUM(CASE WHEN type='B' THEN num END), 0) AS num_B, COALESCE(SUM(CASE WHEN type='C' THEN num END), 0) AS num_C FROM table_name;
上面的代碼中,假設(shè)表格中有type和num兩列數(shù)據(jù),type有A、B、C三種類型,num為具體數(shù)量。這個(gè)查詢語(yǔ)句可以將行數(shù)據(jù)轉(zhuǎn)換為列數(shù)據(jù),以num_A、num_B、num_C的形式輸出各個(gè)類型的數(shù)量。
-- 自聯(lián)結(jié)查詢實(shí)現(xiàn): SELECT t1.type, COALESCE(t1.num, 0) AS num, COALESCE(t2.num, 0) AS num2, COALESCE(t3.num, 0) AS num3 FROM (SELECT type, num from table_name WHERE type='A') AS t1 LEFT JOIN (SELECT type, num from table_name WHERE type='B') AS t2 ON t1.type = t2.type LEFT JOIN (SELECT type, num from table_name WHERE type='C') AS t3 ON t1.type = t3.type;
上面的代碼中,首先使用子查詢將表格中type為A、B、C的行分別查詢出來(lái),并分別命名為t1、t2、t3。然后使用LEFT JOIN自聯(lián)結(jié)查詢將它們合并為一張表,以type列為鍵進(jìn)行合并。最終輸出的結(jié)果包括type列和num、num2、num3三列數(shù)據(jù)。