【问题标题】:SELECT to return duplicate distinct column valuesSELECT 返回重复的不同列值
【发布时间】:2020-03-23 20:34:12
【问题描述】:

试图让查询可以根据其他列中的值复制某些列值。 ID1 列总是有一个值,ID2 和 ID3 可能有也可能没有。表格中的数据如下所示。

RefNum  DetailDesc        ID1        ID2      ID3        HRs
43      Test detail 1.    110011     220022   330033     1.5
43      Test detail 2.    110011     220022   330033     0.75
43      Test detail 3.    110011     220022   NULL       1.25
43      Test detail 4.    110011     220022   NULL       1.5
43      Test detail 5.    110011     NULL     NULL       0.5
43      Test detail 6.    110011     NULL     NULL       2

想要查询此表以显示这样的结果集

RefNum  IDOrder   ID        DetailDesc        HRs
43      1         110011    Test detail 1.    1.5
43      2         220022    Test detail 1.    1.5
43      3         330033    Test detail 1.    1.5
43      1         110011    Test detail 2.    0.75
43      2         220022    Test detail 2.    0.75
43      3         330033    Test detail 2.    0.75
43      1         110011    Test detail 3.    1.25
43      2         220022    Test detail 3.    1.25
43      1         110011    Test detail 4.    1.5
43      2         220022    Test detail 4.    1.5
43      1         110011    Test detail 5.    0.5
43      1         110011    Test detail 6.    2

一直在尝试这个案例选择,并插入到临时表中。我卡住了。

【问题讨论】:

  • 向我们展示你的刺,这样我们就能看到你的想法,

标签: sql sql-server


【解决方案1】:

您可以使用cross apply 取消透视数据:

select t.RefNum, v.IDOrder, v.ID, t.DetailDesc, t.HRs
from t cross apply
     (values (1, t.id1), (2, t.id2), (3, t.id3)
     ) v(idorder, id)
where v.id is not null;

【讨论】:

  • 没错。并且非常快速的回答。谢谢楼主
猜你喜欢
  • 1970-01-01
  • 2014-11-30
  • 2015-12-28
  • 2020-03-10
  • 2021-07-25
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多