MySQL是當(dāng)前最流行的關(guān)系型數(shù)據(jù)庫(kù)系統(tǒng)之一。它支持廣泛的應(yīng)用程序,特別是在Web開(kāi)發(fā)中。
一種關(guān)系型數(shù)據(jù)庫(kù)技術(shù)是交叉表(Pivot Table),也稱為透視表。交叉表允許將表中的行(記錄)轉(zhuǎn)換為列,并且可以進(jìn)行匯總和數(shù)據(jù)聚合。在MySQL中,可以使用“CASE WHEN”和“SUM”函數(shù)來(lái)創(chuàng)建交叉表。
SELECT `product`, SUM(CASE WHEN `month`=1 THEN `sales` ELSE 0 END) AS `Jan`, SUM(CASE WHEN `month`=2 THEN `sales` ELSE 0 END) AS `Feb`, SUM(CASE WHEN `month`=3 THEN `sales` ELSE 0 END) AS `Mar`, SUM(CASE WHEN `month`=4 THEN `sales` ELSE 0 END) AS `Apr`, SUM(CASE WHEN `month`=5 THEN `sales` ELSE 0 END) AS `May`, SUM(CASE WHEN `month`=6 THEN `sales` ELSE 0 END) AS `Jun`, SUM(CASE WHEN `month`=7 THEN `sales` ELSE 0 END) AS `Jul`, SUM(CASE WHEN `month`=8 THEN `sales` ELSE 0 END) AS `Aug`, SUM(CASE WHEN `month`=9 THEN `sales` ELSE 0 END) AS `Sep`, SUM(CASE WHEN `month`=10 THEN `sales` ELSE 0 END) AS `Oct`, SUM(CASE WHEN `month`=11 THEN `sales` ELSE 0 END) AS `Nov`, SUM(CASE WHEN `month`=12 THEN `sales` ELSE 0 END) AS `Dec` FROM `sales_table` GROUP BY `product`
在上面的代碼中,“sales_table”代表銷售數(shù)據(jù)表,包含“product”、“month”和“sales”三個(gè)字段。第一行中,“product”是分組字段。接下來(lái)的12行中,每行都使用“SUM”函數(shù)和“CASE WHEN”語(yǔ)句來(lái)計(jì)算特定月份的銷售總額。最后,“GROUP BY”語(yǔ)句按產(chǎn)品分組,生成透視表。
交叉表在數(shù)據(jù)分析和報(bào)表制作中非常有用。MySQL中的交叉表語(yǔ)法簡(jiǎn)單易懂,有助于開(kāi)發(fā)人員分析大量數(shù)據(jù)并從中得出趨勢(shì)與結(jié)論。