How to put multiple fields into one field

时间:2016-03-04 17:51:56

标签: sql sql-server

I am trying to take 3 different types of Invoices and put them into one field, so i can have one field for invoices, instead of three separate fields with invoice numbers? Here is what i currently have:

**invoice1  invoice2    invoice3**
357744AZ    255589P0109 255589C1108
357744AZ    255589P0109 255589C1208
357744AZ    255589P0209 255589C1108
357744AZ    255589P0209 255589C1208
357744AZ    255589P0908 255589C1108
357744AZ    255589P0908 255589C1208
357744AZ    255589P1008 255589C1108
357744AZ    255589P1008 255589C1208
357744AZ    255589P1108 255589C1108
357744AZ    255589P1108 255589C1208
357744AZ    255589P1208 255589C1108
357744AZ    255589P1208 255589C1208
357744AZ    255589P1308 255589C1108
357744AZ    255589P1308 255589C1208
361507AZ    255589P0109 255589C1108
361507AZ    255589P0109 255589C1208
361507AZ    255589P0209 255589C1108
361507AZ    255589P0209 255589C1208
361507AZ    255589P0908 255589C1108
361507AZ    255589P0908 255589C1208
361507AZ    255589P1008 255589C1108
361507AZ    255589P1008 255589C1208
361507AZ    255589P1108 255589C1108
361507AZ    255589P1108 255589C1208
361507AZ    255589P1208 255589C1108
361507AZ    255589P1208 255589C1208
361507AZ    255589P1308 255589C1108
361507AZ    255589P1308 255589C1208
403349AZ    250432P0112 250432C0112
403349AZ    250432P0113 250432C0112
403349AZ    250432P0114 250432C0112

And i want it to look like this:

**invoice1**
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
357744AZ
255589P0109
255589P0109
255589P0209
255589P0209
255589P0908
255589P0908
255589P1008
255589P1008
255589P1108
255589P1108
255589C1108
255589C1208
255589C1108
255589C1208
255589C1108
255589C1208
255589C1108
255589C1208
255589C1108
255589C1208

All of the invoices are in one field. I cannot find anything online on how to do this? Any help will be helpful, thank you. I am using Sql Server 2012.

4 个答案:

答案 0 :(得分:4)

I like to handle these use cross apply:

select i.*
from t cross apply
     (values (invoice1), (invoice2), (invoice3)
     ) i(invoice);

One nice thing about using apply in this case is that the underlying table is read only once. This only makes a difference if the table is really, really big or a complex query.

答案 1 :(得分:1)

You need UNION

SELECT invoice1
FROM Table
UNION ALL
SELECT invoice2
FROM Table
UNION ALL
SELECT invoice3
FROM Table

答案 2 :(得分:1)

You can use union clause for the same:-

SELECT invoice1 FROM YOUR_TABLE
UNION ALL
SELECT invoice2 FROM YOUR_TABLE
UNION ALL
SELECT invoice3 FROM YOUR_TABLE

答案 3 :(得分:1)

union all will help you

select invoice1 from <tablename>
union all
select invoice2 from <tablename>
union all
select invoice3 from <tablename>
相关问题