我有以下两个表
username data_usage cost
----- ------ ----
user1 50 159
user2 250 376
user3 150 225
username user1 user2 user3
----- ----- ----- -----
data_usage 50 200 150
cost 159 376 225
我想检查两个表的值是否相等,但问题是这样 第一个表的用户名是列名,第二个表的值是
那么无论如何使用PL / SQL在oracle中对这些表进行旋转? 或其他任何方式吗?
输出将是这样的
user1 has different values column name data usage 250 at first table and 200 at table2
答案 0 :(得分:2)
如果数据库版本为> = Oracle 11.2
,则使用pivot和unpivotWITH table1(username,data_usage,cost) AS (
SELECT 'user1', 50, 159 FROM dual UNION ALL
SELECT 'user2', 250, 376 FROM dual UNION ALL
SELECT 'user3', 150, 225 FROM dual),
table2(username,user1,user2,user3) AS (
SELECT 'data_usage', 50, 200, 150 FROM dual UNION ALL
SELECT 'cost', 159, 376, 225 FROM dual)
---
--End of data preparation
---
select tb.username || ' has different values column name data usage '|| tb.data_usage ||' at first table and '|| ta.data_usage ||' at table2' as text
from (select *
from table2
unpivot (val for users in (user1 as 'user1', user2 as 'user2', user3 as 'user3'))
pivot (min(val) for username in ('data_usage' as data_usage, 'cost' as cost))) ta
join table1 tb on (username = users)
WHERE ta.data_usage <> tb.data_usage;
输出继电器:
| TEXT |
|----------------------------------------------------------------------------------------|
| user2 has different values column name data usage 250 at first table and 200 at table2 |
只需使用此查询
select tb.username || ' has different values column name data usage '|| tb.data_usage ||' at first table and '|| ta.data_usage ||' at table2' as text
from (select *
from table2
unpivot (val for users in (user1 as 'user1', user2 as 'user2', user3 as 'user3'))
pivot (min(val) for username in ('data_usage' as data_usage, 'cost' as cost))) ta
join table1 tb on (username = users)
WHERE ta.data_usage <> tb.data_usage;
将table1和table2替换为您的表名