需要帮助在空白字段中填充填充数据的字段

时间:2012-01-30 13:21:01

标签: sql sql-server sql-server-2008

我希望有人可以帮助我查询我一直在写的问题。我仍然是sql的新手,所以如果我解释错误,请告诉我。

我有一个包含部件号字段的表,以及30个描述字段和30个描述值字段。我试图以特定格式返回记录,其中在填充字段前面没有空白值的记录。例如,如果我有以下记录:

Part_Number|Description_1|Description_1_Value|Description_2|Description_2_Value|Description_3|Description_3_Value
123|Color|Red|Material|Wood|Quantity|
456|Color||Material|Steel|Quantity|
789|Color|Black|Material||Quantity|1

我想返回以下结果:

Part_Number|Description 1|Description 2
123|Quantity
456|Color|Quantity
789|Material

以下是我正在使用的查询:

SELECT [Part_Number]
,isnull(case when [Description_1_Value] is null then [Description_1] else '' end,'') 'Description 1'
,isnull(case when [Description_2_Value] is null then [Description_2] else '' end,'') 'Description 2'
,isnull(case when [Description_3_Value] is null then [Description_3] else '' end,'') 'Description 3'
FROM [MyTable]

我对此查询的问题是它允许填充的字段之间的空白字段。将所有填充字段移到所有空白字段左侧的最佳方法是什么?我有30列,可能有也可能没有数据。

提前谢谢!

编辑:我正在使用MS SQL Server Management Studio 2008

2 个答案:

答案 0 :(得分:2)

将值插入临时表。

更新行以解决空白问题。

这是一个完整的例子(我将在temp table#table2和aftwerwords中插入值,我将更新所有行):

create table #test (
id int,
desc1 int null,
desc2 int null,
desc3 int null
)

create table #test2 (
id int,
desc1 varchar(10) null,
desc2 varchar(10) null,
desc3 varchar(10) null
)


insert into #test values (123, 1, 1, NULL), (456, NULL, NULL, 1), (789, 1, NULL, 1)


insert into #test2
select id, 'desc1', null, null from #test
where desc1 is null

insert into #test2
select id, null, 'desc2', null from #test
where desc2 is null

insert into #test2
select id, null, null, 'desc3' from #test
where desc3 is null


update #test2
set desc1 = isnull(desc2, desc3),
desc2 = null
where desc1 is null

update #test2
set desc2 = isnull(desc3, null),
desc3 = null
where desc2 is null

select * from #test2

drop table #test
drop table #test2

答案 1 :(得分:2)

您的结果集与列标签不匹配。除非您希望它们是“缺少描述1”或类似的东西。示例:第3行,“材料”不是“描述1”,但您可以在该列中使用它。

如果希望将值分开,则希望将所有值保留在同一列中,并将值与管道字符连接起来。

SELECT [Part_Number] 
    ,isnull(case when [Description_1_Value] is null 
                 then [Description_1] + '|' 
                 else '' 
            end
      ,'') 
     + isnull(case when [Description_2_Value] is null 
                     then [Description_2] + '|' 
                     else '' 
                end,'')  
     + isnull(case when [Description_3_Value] is null 
                     then [Description_3] + '|' 
                     else '' 
                end,'') as 'Missing Description'  
FROM [MyTable]

您可能需要考虑重新设计此表。你为什么不能有专栏:'颜色','数量','材料'?或者有一个名为Descritions的单独表:列:Part_Number,Description_Label,Description_Value。如果您的目标只是获取缺失值列表,您可以:

Select * from Descriptions Where Description_Value Is Null;
相关问题