sql:具有一列的分组依据

kd3sttzy  于 2021-06-26  发布在  Hive
关注(0)|答案(3)|浏览(305)

我有一张这样的table:

name    id1     id2     id3     id4
Mark    aaa     null    null    null
Mark    null    bbb     null    null
Mark    null    null    null    null
John    null    null    eee     null
John    ccc     null    null    null
John    null    ddd     null    null
John    null    null    null    null

所以,我有5列,如,name,id1,id2,id3和id4,都是字符串值。我需要去一个小组的名字只;它将包含除空值以外的所有值。所以最终的输出是这样的:

name    id1     id2     id3     id4
    Mark    aaa     bbb     null    null
    John    ccc     ddd     eee     null

有人能帮我吗?

11dmarpk

11dmarpk1#

用这样的方法:

select 
  name,
  max(id1) id1,
  max(id2) id2,
 max(id3) id3,
  max(id4) id4
from
(
  select name, id1, id2, id3, id4,
    row_number() over(partition by name
                      order by name) seq
  from yourtable
) d
group by name
c0vxltue

c0vxltue2#

使用 MAX :

SELECT
    name,
    MAX(id1) AS id1,
    MAX(id2) AS id2,
    MAX(id3) AS id3,
    MAX(id4) AS id4
FROM tbl
GROUP BY name;
ve7v8dk2

ve7v8dk23#

字符串上的最大值。。。z大于a。任何字符串都大于null。别忘了这一组

create table #test(
name varchar(10),
id1 varchar(10),
id2 varchar(10),
id3 varchar(10),
id4 varchar(10)
)

INSERT INTO #test SELECT 'Mark', 'aaa', null, null, null;
INSERT INTO #test SELECT 'Mark', null, 'bbb', null, null;
INSERT INTO #test SELECT 'Mark', null, null, null, null
INSERT INTO #test SELECT 'John', null, null, 'eee', null
INSERT INTO #test SELECT 'John', 'ccc', null, null, null
INSERT INTO #test SELECT 'John', null, 'ddd', null, null
INSERT INTO #test SELECT 'John', null, null, null, null

SELECT
    name,
    MAX(id1) AS id1,
    MAX(id2) AS id2,
    MAX(id3) AS id3,
    MAX(id4) AS id4
FROM #test
Group By name

drop table #test

相关问题