2011-12-23 63 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

相关问题