2017-06-07 67 views
-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 

查詢返回的最大值 像:

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

我需要選擇查詢是這樣的:

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

我該怎麼辦? PLZ?

+5

你嘗試過什麼嗎?堆棧溢出不是免費的代碼寫入服務。 –

+0

首先嚐試以正確的方式保存數據。聚合會達到目的,但這不是解決方案,表本身是問題 – GauravKP

回答

1

一個簡單的辦法是讓最高如下:

Select Id, Max(name) as [Name], Max(age) as Age, Max(Tel) as Tel 
from yourtable 
Group by Id 
+0

謝謝,但有點不同! –

+0

你在找什麼不同? –

+0

我需要最後一條記錄爲空 –

0

下面就以3列的最後一個非空值結合了迂迴的方式:

-- Using a table variable for test data 
declare @Test table (tableId int identity(1,1), id int, name varchar(100), age int, tel varchar(30)); 
insert into @Test (id, name, age, tel) values 
(1,'Frank',40,null), 
(1,null,50,'7834xx'), 
(1,'Alex',null,null), 
(1,null,20,null), 
(2,'James',null,'4121xx'); 

select n.id, n.name, a.age, t.tel 
from (
    select top(1) with ties id, name 
    from @Test 
    where name is not null 
    order by row_number() over (partition by id order by tableId desc) 
) n 
inner join (
    select top(1) with ties id, age 
    from @Test 
    where age is not null 
    order by row_number() over (partition by id order by tableId desc) 
) a on (n.id = a.id) 
inner join (
    select top(1) with ties id, tel 
    from @Test 
    where tel is not null 
    order by row_number() over (partition by id order by tableId desc) 
) t on (n.id = t.id); 

-- or by re-using a CTE 
;with CTE AS (
    select * , 
    row_number() over (partition by id, iif(name is not null,1,0) order by tableId desc) as rn_name, 
    row_number() over (partition by id, iif(age is not null,1,0) order by tableId desc) as rn_age, 
    row_number() over (partition by id, iif(tel is not null,1,0) order by tableId desc) as rn_tel 
    from @Test 
) 
select n.id, n.name, a.age, t.tel 
from CTE n 
join CTE a on (a.id = n.id and a.age is not null and a.rn_age = 1) 
join CTE t on (t.id = n.id and t.tel is not null and t.rn_tel = 1) 
where (n.name is not null and n.rn_name = 1); 

結果:

╔════╦══════╦═════╦════════╗ 
║ id ║ name ║ age ║ tel ║ 
╠════╬══════╬═════╬════════╣ 
║ 1 ║ Alex ║ 20 ║ 7834xx ║ 
╚════╩══════╩═════╩════════╝ 
0

感謝您的回答和幫助。 我覺得這個查詢:

SELECT TOP 10
(SELECT頂(1)名稱FROM test1的其中id = 1,名稱不爲空,以便通過自動識別DESC),如姓名 ,(SELECT頂(1)年齡test1其中id = 1,年齡不爲空,按照自動識別號desc排序)作爲年齡 ,(SELECT top(1)Tel FROM test1其中id = 1,Tel不是null按自動識別順序排序)作爲Telephon FROM [dbo]。 [test1] group by id

其工作! 但我的事情也有另一種簡單的方法,也許是這樣的:

選擇ID,NOTNULL(名稱)[名稱],NOTNULL(年齡)的年齡,NOTNULL(電話)的電話 從yourtable集團通過標識

???