2017-06-07 82 views
0

的問題是,如果要輸入太多記錄多行1列,SQL服務器

  | id | name | age | Tel 
------------------------------------------ 
     1 | 1 | Frank | 40  | null 
     2 | 1 | null | 50  | 7834xx 
     3 | 1 | Alex | null | null 
     4 | 1 | null | 20  | null 
     5 | 2 | James | null | 4121xx 

我的查詢:

select id, max(name) as name, max(age) as age, max(tel) as tel 
from Table group by id; 

結果=返回最大值像:

  | id | name | age | Tel 
------------------------------------------ 
     1 | 1 | Frank | 50  | 7834xx 

但我需要選擇這樣的查詢: 例如:(也許): select id,lastRow sNotNull(name)作爲姓名,lastRowsNotNull(年齡)作爲年齡,lastRowsNotNull(tel)作爲電話從Table group by id;

  | id | name | age | Tel 
------------------------------------------ 
     1 | 1 | Alex | 20  | 7834xx 

我該怎麼辦?認罪?

+0

什麼是第一列?在那個ID之前?你有那個序列號列嗎? –

+0

20歲是如何在年齡列的最大數量?您正在查找的結果似乎與數據不匹配。還有其他要求嗎? –

+0

id是idenety列。 –

回答

0
drop table if exists dbo.TableC; 

create table dbo.TableC (
Ident int primary key 
, Id int 
, name varchar(100) 
, age int 
, Tel varchar(100) 
); 

insert into dbo.TableC (Ident, Id, name, age, Tel) 
values (1, 1, 'Frank', 40, null) 
, (2, 1, null, 50, '7834xx') 
, (3, 1, 'Alex', null, null) 
, (4, 1, null, 20, null) 
, (5, 2, 'James', null, '4121xx'); 

select 
* 
from (
select 
    MIN(t.Ident) as Ident 
    , t.id 
from dbo.TableC t 
group by t.Id 
) t 
outer apply (
    select 
     top (1) 
     tn.name 
    from dbo.TableC tn 
    where tn.name is not null 
     and tn.Id = t.Id 
    order by tn.Ident desc 
) tname 
outer apply (
    select 
     top (1) 
     ta.age 
    from dbo.TableC ta 
    where ta.age is not null 
     and ta.Id = t.Id 
    order by ta.Ident desc 
) tage 
outer apply (
    select 
     top (1) 
     tt.tel 
    from dbo.TableC tt 
    where tt.Tel is not null 
     and tt.Id = t.Id 
    order by tt.Ident desc 
) ttel 
+0

謝謝,它太複雜了!我認爲還有另一種簡單方法,也許:select id,lastRows!null(name)作爲名稱,... from Table group by id; 我需要的是不是空的 –