Oracle SQL 转置数据
Oracle SQL Transpose data
我有一个要求,我的数据来自这样的表
country total_population number_of_cities number_of_airports
US 1,000,000,000 500 25
UK 2,000,000,000 400 20
这是动态数据。我需要显示的结果是这样的
US UK
total_population 1,000,000,000 2,000,000,000
number_of_cities 500 400
number_of_airports 25 20
我怎样才能做到这一点?
非常感谢任何帮助或指点。
您可以组合使用 MAX
、CASE
和 UNION ALL
。
SELECT 'total_population' metric,
MAX(CASE
WHEN country = 'US' THEN total_population
END) US,
MAX(CASE
WHEN country = 'UK' THEN total_population
END) UK
FROM yourtable
UNION ALL
SELECT 'number_of_cities' metric,
MAX(CASE
WHEN country = 'US' THEN number_of_cities
END) US,
MAX(CASE
WHEN country = 'UK' THEN number_of_cities
END) UK
FROM yourtable
UNION ALL
SELECT 'number_of_airports' metric,
MAX(CASE
WHEN country = 'US' THEN number_of_airports
END) US,
MAX(CASE
WHEN country = 'UK' THEN number_of_airports
END) UK
FROM yourtable;
这是需求的解决方案。它基本上需要交换行和列。这可以通过先取消旋转然后再旋转回来来实现。这是查询
select *
from (
select
country,
total_population, number_of_cities, number_of_airports
FROM yourtable
) unpivot ( val for stats in (total_population, number_of_cities, number_of_airports))
pivot (sum(val) for country in ('US', 'UK'));
我有一个要求,我的数据来自这样的表
country total_population number_of_cities number_of_airports
US 1,000,000,000 500 25
UK 2,000,000,000 400 20
这是动态数据。我需要显示的结果是这样的
US UK
total_population 1,000,000,000 2,000,000,000
number_of_cities 500 400
number_of_airports 25 20
我怎样才能做到这一点? 非常感谢任何帮助或指点。
您可以组合使用 MAX
、CASE
和 UNION ALL
。
SELECT 'total_population' metric,
MAX(CASE
WHEN country = 'US' THEN total_population
END) US,
MAX(CASE
WHEN country = 'UK' THEN total_population
END) UK
FROM yourtable
UNION ALL
SELECT 'number_of_cities' metric,
MAX(CASE
WHEN country = 'US' THEN number_of_cities
END) US,
MAX(CASE
WHEN country = 'UK' THEN number_of_cities
END) UK
FROM yourtable
UNION ALL
SELECT 'number_of_airports' metric,
MAX(CASE
WHEN country = 'US' THEN number_of_airports
END) US,
MAX(CASE
WHEN country = 'UK' THEN number_of_airports
END) UK
FROM yourtable;
这是需求的解决方案。它基本上需要交换行和列。这可以通过先取消旋转然后再旋转回来来实现。这是查询
select *
from (
select
country,
total_population, number_of_cities, number_of_airports
FROM yourtable
) unpivot ( val for stats in (total_population, number_of_cities, number_of_airports))
pivot (sum(val) for country in ('US', 'UK'));