MySQL中的橫向查詢是一種查詢方式,它是根據(jù)表格的列來組織結(jié)果的。在這種查詢中,數(shù)據(jù)集合被轉(zhuǎn)換成了表格樣式的結(jié)果。這種查詢方式有時(shí)也被稱為“旋轉(zhuǎn)表格”。
SELECT MAX(CASE WHEN month='Jan' THEN revenue END) AS Jan, MAX(CASE WHEN month='Feb' THEN revenue END) AS Feb, MAX(CASE WHEN month='Mar' THEN revenue END) AS Mar, MAX(CASE WHEN month='Apr' THEN revenue END) AS Apr, MAX(CASE WHEN month='May' THEN revenue END) AS May, MAX(CASE WHEN month='Jun' THEN revenue END) AS Jun, MAX(CASE WHEN month='Jul' THEN revenue END) AS Jul, MAX(CASE WHEN month='Aug' THEN revenue END) AS Aug, MAX(CASE WHEN month='Sep' THEN revenue END) AS Sep, MAX(CASE WHEN month='Oct' THEN revenue END) AS Oct, MAX(CASE WHEN month='Nov' THEN revenue END) AS Nov, MAX(CASE WHEN month='Dec' THEN revenue END) AS Dec FROM sales WHERE year=2021;
在以上示例中,我們查詢了2021年每個(gè)月的銷售收入,然后將結(jié)果旋轉(zhuǎn)為表格樣式。我們使用了12個(gè)CASE語句來標(biāo)識(shí)每個(gè)月份的銷售收入,并使用MAX函數(shù)來計(jì)算每個(gè)月份的最大值。這種查詢方式可以將結(jié)果變?yōu)橐子谧x取的表格樣式,使得數(shù)據(jù)分析更加方便。
橫向查詢?cè)谀承┣闆r下非常有用,尤其是在需要匯總數(shù)據(jù)并進(jìn)行比較的場景中。但也應(yīng)該注意,在執(zhí)行橫向查詢時(shí)可能會(huì)增加查詢的復(fù)雜度和執(zhí)行時(shí)間。