我有一张这样的表:
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列,名称,id1,id2,id3和id4 -all是字符串值。我只需要一个GROUP BY的名字;除了null值之外,它将包含所有值。所以最终输出将是这样的:
name id1 id2 id3 id4
Mark aaa bbb null null
John ccc ddd eee null
有人可以帮我这么做吗?
答案 0 :(得分:3)
Use MAX
:
SELECT
name,
MAX(id1) AS id1,
MAX(id2) AS id2,
MAX(id3) AS id3,
MAX(id4) AS id4
FROM tbl
GROUP BY name;
答案 1 :(得分:1)
使用类似的东西:
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
答案 2 :(得分:1)
字符串上的最大值... Z大于A.任何字符串都大于null。 别忘了GROUP BY
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