簡體   English   中英

什么SELECT語句將從表行中獲取非零值?

[英]What SELECT statement will get the non-zero values from table rows?

如果我在27列的表中有多行,這些都是這樣的整數

id_1    id_2    id_3    id_4    id_5    id_6    id_7    id_8    id_9    id_10   id_11   id_12   id_13   id_14   id_15   id_16   id_17   id_18   id_19   id_20   id_21   id_22   id_23   id_24   id_25   id_26   id_27
0       2       0       4       5       0       0       8       0       10      0       0       0       14      0       0       17      0       0       0       21      0       0       0       0       0       0

我想運行一個SELECT語句來獲得最多8列> 0(絕不會超過8)的最佳或至少是功能性的方法? 如果沒有8個值> 0,則允許NULLS。 因此,上面的結果表將是。

col1 col2 col3 col4 col5 col6 col7 col8
2    4    5    8    10   14   17   21

如果您可以忍受列中的結果,那么這是一種簡單的方法:

select top 8 v.col
from table t cross apply
     values ((t.id_1), (t.id_2), . . ., (t.id_27)) as v(col)
where v.col <> 0;

所有數據都獲得8。 如果你想要每行8個,那么你需要一個行標識符。 你可以使用窗口函數:

select t.id, v.col
from (select t.id, v.col,
             row_number() over (partition by t.id order by (select null)) as seqnum
      from table t cross apply
           values ((t.id_1), (t.id_2), . . ., (t.id_27)) as v(col)
      where col <> 0
     ) t
where seqnum <= 8;

最后,您可以將它們轉回一行。 我傾向於使用條件聚合來做到這一點:

select t.id,
       max(case when seqnum = 1 then v.col end) as val1,
       max(case when seqnum = 2 then v.col end) as val2,
       max(case when seqnum = 3 then v.col end) as val3,
       max(case when seqnum = 4 then v.col end) as val4,
       max(case when seqnum = 5 then v.col end) as val5,
       max(case when seqnum = 6 then v.col end) as val6,
       max(case when seqnum = 7 then v.col end) as val7,
       max(case when seqnum = 8 then v.col end) as val8
from (select t.id, v.col,
             row_number() over (partition by t.id order by (select null)) as seqnum
      from table t cross apply
           values ((t.id_1), (t.id_2), . . ., (t.id_27)) as v(col)
      where col <> 0
     ) t
where seqnum <= 8
group by id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM