2012-09-12 38 views
2

我在一個表中有超過1行屬於同一個ID。選擇具有最大列數據的行

我想選擇更多列包含數據的行。

例如。

我的數據是這樣的

select * from my_table where id=1 

PK Id Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 
101 1 NULL NULL NULL XX  NULL NULL NULL NULL NULL NULL 
102 1 NULL NULL NULL XX  YY  NULL ZZ  NULL NULL NULL 
103 1 NULL AA  NULL NULL NULL NULL NULL NULL NULL NULL 
104 1 NULL NULL NULL NULL NULL BB  NULL NULL NULL NULL 
105 1 NULL NULL NULL NULL NULL NULL NULL CC  NULL NULL 

我想查詢,這將給我輸出這樣的ID = 1: -

PK Id Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 
102 1 NULL NULL NULL XX  YY  NULL ZZ  NULL NULL NULL 
+2

規範化你的數據結構。 – podiluska

+0

@podiluska完全同意你 –

+0

@podiluska:即使我同意你的看法。但我不能這樣做。所以我必須照原樣。 –

回答

2

在哪裏pk是你的主...

select * 
from YourBadlyStructuredTable 
where pk in (
    select top 1 pk from YourBadlyStructuredTable 
    unpivot (col for z in (col1,col2,col3, ...))u 
    where id=1 
    group by pk 
    order by COUNT(*) desc 
) 

如果您不能指定列名...

select 
    top 1 
    HorribleTable.* 
from 
(
    select 
     xmldata.value('(/x2/@PK)[1]','int') as PK1, 
     xmldata.value('(/x2/@Id)[1]','int') as ID1, 
     xmldata.value('count(/x2/@*)','int') as cnt 
     from 
     (
    select  
     t.x.query('.') as xmldata    
    from 
     ( select convert(xml,(select * from HorribleTable for xml raw('x2'))) as x1) v 
      cross apply 
     v.x1.nodes('/x2') t(x) 
    ) v 
) v 
    inner join HorribleTable on v.PK1 = HorribleTable.pk 
where ID1 = 1 
order by cnt desc 
+0

我喜歡錶名,我一定會告訴我們的DBA。 –

+0

我可以看到解決方案的工作。但實際上我有一個53列的表格,我想要一個通用的解決方案來解決這類問題。我不想明確提及所有列。 –

+0

請參閱上面的修改。這很可怕。 – podiluska

1

試試這個:

with cte as (select *,case when col1 is not null then 1 else 0 end+ 
      case when col2 is not null then 1 else 0 end+ 
      case when col3 is not null then 1 else 0 end+ 
      case when col4 is not null then 1 else 0 end+ 
      case when col5 is not null then 1 else 0 end+ 
      case when col6 is not null then 1 else 0 end+ 
      case when col7 is not null then 1 else 0 end+ 
      case when col8 is not null then 1 else 0 end+ 
      case when col9 is not null then 1 else 0 end+ 
      case when col10 is not null then 1 else 0 end as col_count 
    from my_table where id=1) 
    select * from cte where col_count =(select MAX(col_count) from cte) 
+0

我希望該行不是每列的最大值。 –

+0

@ G.S:我已經更新了我的答案.. plz檢查它 –

+0

我可以看到解決方案的工作。但實際上我有一個53列的表格,我想要一個通用的解決方案來解決這類問題。我不想明確提及所有列 –

0
;WITH CTE as ( 
select pk,isnull(col1,'')+isnull(col2,'')+isnull(col3,'')+isnull(col4,'')+isnull(col5,'')+ 
    isnull(col6,'')+isnull(col7,'')+isnull(col8,'')+isnull(col9,'')+isnull(col10,'') as res 
    from tbl4 where id=1) 


select * from tbl4 where pk in(select pk from CTE where len(res)=(select max(len(res)) from CTE))