一道hive SQL面試題


 

一、hive中實現方法

基表:

組表:

gt

 

gid

gname

1001

g1

1002

g2

1003

g3

create table g(

gid int,

gname string

)row format delimited fields terminated by '\t'

stored as textfile;

用戶表:

ut

 

uid

uname

10001

u1

10002

u2

10003

u3

10004

u4

10005

u5

10006

u6

10007

u7

10008

u8

10009

u9

10010

u10

create table u(

uid int,

uname string

)row format delimited fields terminated by '\t'

stored as textfile;

權限表:

gu

 

gid

uid

1001

10002,10001,10003,10009

1002

10004,10005,10006

1003

10007,10008,10010

create table gu(

gid int,

uid string

)row format delimited fields terminated by '\t'

stored as textfile;

組表gt中記錄了組的信息組id和組名稱,用戶表記錄了用戶基本信息用戶id和用戶名稱,gu是組表和用戶表的關系,記錄了每一個組內與用戶對應關系,其中僅記錄id信息。題目是根據gt和ut表將gu表中的所有id轉換為名稱?

我寫的SQL是:

select t.gname,concat_ws(',',collect_set(t.uname)) from (

select g.gname,u.uname

from (

select gid,s_uid from gu

lateral view explode(split(uid,',')) uid as s_uid) temp,g,u

where temp.gid=g.gid and temp.s_uid=u.uid) t

group by t.gname;

運行結果如下:

hive> select t.gname,concat_ws(',',collect_set(t.uname)) from (

    > select g.gname,u.uname

    > from (

    > select gid,s_uid from gu

    > lateral view explode(split(uid,',')) uid as s_uid) temp,g,u

    > where temp.gid=g.gid and temp.s_uid=u.uid) t

    > group by t.gname;

OK

g1 u2,u1,u3,u9

g2 u4,u5,u6

g3 u7,u8,u10

二、oracle中實現方法

1、建立基表

create table g(

gid number(10),

gname varchar2(20)

)

create table u(

usrid number(10),

uname varchar2(20)

)

create table gu(

gid number(10),

usrid varchar2(200)

)

我所實現的sql方法如下:

select g.gname,

(select wm_concat(uname) from u where instr(gu.usrid, u.usrid) > 0)

from gu, g

where gu.gid = g.gid;

執行結果:

SQL> select g.gname,

  2         (select wm_concat(uname) from u where instr(gu.usrid, u.usrid) > 0)

  3    from gu, g

  4   where gu.gid = g.gid;

GNAME                (SELECTWM_CONCAT(UNAME)FROMUWH

-------------------- --------------------------------------------------------------------------------

g1                   u1,u2,u3,u9

g2                   u4,u5,u6

g3                   u7,u8,u10


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM