Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

SQL Server row to columns

I have data in a SQL Table with the following structure:

Engine_No Date  Process Bolt_No1 B1Value1 B1Value2 B1Value3 Bolt_No2 B2Value1 B2Value2 B2Value3  Bolt_No3 B3Value1 B3Value2 B3Value3 Bolt_No4 B4Value1 B4Value2 B4Value3

I want to display the following results of a query:

SR NO  Engine_No Date  Process B1Bolt_No1 B1Value1 B1Value2 B1Value3          
SR NO  Engine_No Date  Process B2Bolt_No2 B2Value1 B2Value2 B2Value3   
SR NO  Engine_No Date  Process B3Bolt_No3 B3Value1 B3Value2 B3Value3  
SR NO  Engine_No Date  Process B4Bolt_No4 B4Value1 B4Value2 B4Value3

Can someone suggest a Query that achieves this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming the values are actually stored in valid column names, then the simplest way is to use union all. However, a more performing way is unpivot or cross apply:

select t.Engine_No, t.Date, t.Process, b.Bolt_No, b.Value1, b.Value2, b.Value3 
from t cross apply
     (values (Bolt_No1, Value1_1 Value1_2 Value1_3),
             (Bolt_No2, Value2_1 Value2_2 Value2_3),
             (Bolt_No3, Value3_1 Value3_2 Value3_3),
             (Bolt_No4, Value4_1 Value4_2 Value4_3)
     ) b(Bolt_No, Value1 Value2 Value3);

I have no idea what SR NO is. It is not mentioned in the data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...