将行转换为列redshift

时间:2018-08-14 11:47:04

标签: amazon-web-services amazon-redshift

我有下表:

 grantor | grantee | table_catalog | table_schema | table_name | privilege_type | is_grantable | with_hierarchy

 james   | james   | dev           | test         | rest       | SELECT         | NO           | NO
 james   | james   | dev           | test         | rest       | DELETE         | NO           | NO
 james   | james   | dev           | test         | rest       | INSERT         | NO           | NO
 james   | james   | dev           | test         | rest       | UPDATE         | NO           | NO
 james   | james   | dev           | test         | rest       | REFERENCES     | NO           | NO
 james   | james   | dev           | test         | rest       | RULE           | NO           | NO
 james   | james   | dev           | test         | rest       | TRIGGER        | NO           | NO
 james   | yondo   | dev           | test         | rest       | SELECT         | YES          | NO
 james   | yondo   | dev           | test         | rest       | INSERT         | YES          | NO

我想将表生成为:

 grantee | table_name |   select   |   insert   |   delete   | update     | references | rule       | trigger
james   | rest       | TRUE:FALSE | TRUE:FALSE | TRUE:FALSE | TRUE:FALSE | TRUE:FALSE | TRUE:FALSE | TRUE:FALSE
yondo   | rest       | TRUE:TRUE | TRUE:TRUE | FALSE:FALSE | TRUE:FALSE | TRUE:FALSE | FALSE:FALSE | FALSE:FALSE

我尝试过:

SELECT grantee, table_name,
    CASE WHEN privilege_type = 'SELECT' AND is_grantable='YES' THEN 'TRUE:TRUE' 
        ELSE 'TRUE:FALSE' END as select, 
        CASE WHEN privilege_type = 'INSERT' AND is_grantable='YES' THEN 'TRUE:TRUE' 
        ELSE 'TRUE:FALSE' END as insert, 
        CASE WHEN privilege_type = 'DELETE' AND is_grantable='YES' THEN 'TRUE:TRUE' 
        ELSE 'TRUE:FALSE' END as delete
    FROM information_schema.table_privileges WHERE table_schema='test';

但不起作用。什么是解决方案

1 个答案:

答案 0 :(得分:0)

由于您希望每个granteetable_name输出一行,因此需要GROUP BY grantee, table_name

SELECT
  grantee,
  table_name,
  CASE WHEN SUM(CASE WHEN privilege_type = 'SELECT' AND is_grantable='YES' THEN 1 END) > 1 THEN 'TRUE:TRUE' ELSE 'TRUE:FALSE' END as select, 
  CASE WHEN SUM(CASE WHEN privilege_type = 'INSERT' AND is_grantable='YES' THEN 1 END) > 1 THEN 'TRUE:TRUE' ELSE 'TRUE:FALSE' END as insert, 
  CASE WHEN SUM(CASE WHEN privilege_type = 'DELETE' AND is_grantable='YES' THEN 1 END) > 1 THEN 'TRUE:TRUE' ELSE 'TRUE:FALSE' END as delete
FROM information_schema.table_privileges
GROUP BY grantee, table_name
WHERE table_schema='test';

(我没有测试它,所以不能保证!)

上面的操作是在计算所需条件是否存在,然后每列生成一个值。