2011-12-23 64 views
2

如何使用SQL Server獲取單個行,其中唯一非空值是通過所有選定的一致非空值行。如何將多個行合併爲一個行值不同的空值

A B  C  D 
10 NULL text NULL 
4 abc text NULL 
4 def text NULL 

應該給下面一行:

A B  C  D 
NULL NULL text NULL 
+0

這是編輯的多個行當在形式使用的查詢:填充有值的唯一字段是具有在整個選擇相同的值的那些。 – Daniel 2011-12-23 10:03:37

回答

3
declare @t table(A int, b varchar(10), c varchar(max), d int) 

insert @t values(10, null, 'text', null) 
insert @t values(4, 'abc', 'text', null) 
insert @t values(10, 'def', 'text', null) 


select case when max(rna) > 1 then null else min(a) end, 
case when max(rnb) > 1 then null else min(b) end, 
case when max(rnc) > 1 then null else min(c) end, 
case when max(rnd) > 1 then null else min(d) end 
from 
(
select rna = rank() over(order by a), 
rnb = rank() over(order by b), 
rnc = rank() over(order by c), 
rnd = rank() over(order by d), 
a, b,c,d 
from @t 
) e 

如果將文本列替換爲varchar(max)的列類型。文本列已過時。

首先想到使用count(distinct col1),但它不計入空值。

select count(distinct a) from (select cast(null as int) a) b 

返回0行

+0

很好玩RANK() – MatBailie 2011-12-23 10:31:13

+0

你們真是太神奇了!非常感謝你的大力幫助! – Daniel 2011-12-23 10:48:38

4
create table #t (col1 int, col2 char(3), col3 char(4), col4 int) 
go 
insert into #t select 10, null, 'text', null 
insert into #t select 4, 'abc', 'text', null 
insert into #t select 4, 'def', 'text', null 
go 

select 
    case when count(distinct isnull(col1, 0)) > 1 then null else max(col1) end as 'col1', 
    case when count(distinct isnull(col2, '')) > 1 then null else max(col2) end as 'col2', 
    case when count(distinct isnull(col3, '')) > 1 then null else max(col3) end as 'col3', 
    case when count(distinct isnull(col4, 0)) > 1 then null else max(col4) end as 'col4' 
from 
    #t 
go 

drop table #t 
go 

編輯:我添加ISNULL處理由t-clausen.dk確定的問題,但是這隻會工作,如果「默認'值(即零和空字符串)不會出現在實際數據中。

Daniel對數據類型的評論也是正確的,但由於我們不知道涉及的數據類型,因此建議替代方案並不容易。提供使用真實數據類型的自包含測試腳本是提出類似問題的最佳方法。

+0

我正在考慮這樣的解決方案。問題是「空」沒有被計算在內。如果刪除最後一個插入,您將看到我的意思 – 2011-12-23 10:07:37

+0

count()不適用於所有類型。例如,它不適用於ntext列。 – Daniel 2011-12-23 10:08:31

+0

@丹尼爾 - 文字,ntext和圖像都已棄用,不應使用。改爲使用VARCHAR(max)NVARCHAR(max)和VARBINARY(max)。你真的有任何列是不贊成使用的類型? – MatBailie 2011-12-23 10:18:39

2
SELECT 
    CASE WHEN COUNT(DISTINCT col1) = 1 
      AND COUNT(col1) = COUNT(*) 
     THEN MIN(col1) 
    END AS col1 
    , CASE WHEN COUNT(DISTINCT col2) = 1 
      AND COUNT(col2) = COUNT(*) 
     THEN MIN(col2) 
    END AS col2 
    , CASE WHEN COUNT(DISTINCT col3) = 1 
      AND COUNT(col3) = COUNT(*) 
     THEN MIN(col3) 
    END AS col3 
    , CASE WHEN COUNT(DISTINCT col4) = 1 
      AND COUNT(col4) = COUNT(*) 
     THEN MIN(col4) 
    END AS col4 
FROM 
    tableX 
+0

+1真的很好很簡單, – 2011-12-23 14:18:14

+0

@ t-clausen.dk:Thnx。COUNT(DISTINCT column)= 1'也可以用'MIN(column)= MAX(column)'替代' – 2011-12-23 17:31:40

相關問題