Oracle行轉列函式Listagg()和wm_co…
Oracle行轉列函式Listagg()和wm_concat(column)函式
這是一個Oracle的行轉列函式:LISTAGG()
先看示例程式碼:
Sql程式碼
WITH TEMP AS
(SELECT 'China' NATION, 'Guangzhou' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Shanghai' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Beijing' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'New York' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'Bostom' CITY
FROM DUAL
UNION ALL
SELECT 'Japan' NATION, 'Tokyo' CITY
FROM DUAL)
SELECT NATION, LISTAGG(CITY, ',') WITHIN GROUP(ORDER BY CITY)
FROM TEMP
GROUP BY NATION;
這是最基礎的用法:
LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)
用法就像聚合函式一樣,通過Group by語句,把每個Group的一個欄位,拼接起來。
非常方便。
同樣是聚合函式,還有一個高階用法:
就是over(partition by XXX)
也就是說,在你不使用Group by語句時候,也可以使用LISTAGG函式:
Sql程式碼
WITH TEMP AS
(SELECT 500 POPULATION, 'China' NATION, 'Guangzhou' CITY
FROM DUAL
UNION ALL
SELECT 1500 POPULATION, 'China' NATION, 'Shanghai' CITY
FROM DUAL
UNION ALL
SELECT 500 POPULATION, 'China' NATION, 'Beijing' CITY
FROM DUAL
UNION ALL
SELECT 1000 POPULATION, 'USA' NATION, 'New York' CITY
FROM DUAL
UNION ALL
SELECT 500 POPULATION, 'USA' NATION, 'Bostom' CITY
FROM DUAL
UNION ALL
SELECT 500 POPULATION, 'Japan' NATION, 'Tokyo' CITY
FROM DUAL)
SELECT POPULATION,
NATION,
CITY,
LISTAGG(CITY, ',') WITHIN GROUP(ORDER BY CITY) OVER(PARTITION BY NATION) RANK
FROM TEMP;
總結:LISTAGG()把它當作SUM()函式來使用就可以了。
oracle wm_concat(column)函式的使用
格式一:
WITH TEMP AS
(SELECT 'China' NATION, 'Guangzhou' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Shanghai' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Beijing' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'New York' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'Bostom' CITY
FROM DUAL
UNION ALL
SELECT 'Japan' NATION, 'Tokyo' CITY
FROM DUAL)
SELECT NATION, WMSYS.WM_CONCAT(CITY) CITY_SUM
FROM TEMP GROUP BY NATION;
格式二:
WITH TEMP AS
(SELECT 'China' NATION, 'Guangzhou' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Shanghai' CITY
FROM DUAL
UNION ALL
SELECT 'China' NATION, 'Beijing' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'New York' CITY
FROM DUAL
UNION ALL
SELECT 'USA' NATION, 'Bostom' CITY
FROM DUAL
UNION ALL
SELECT 'Japan' NATION, 'Tokyo' CITY
FROM DUAL)
SELECT NATION, WMSYS.WM_CONCAT(NATION||'的'||CITY) CITY_SUM
FROM TEMP GROUP BY NATION;