问题
I have this table:
id fName lName Address PostCode ContactNumber
-----------------------------------------------------
1 Tom Daley London EC1 4EQ 075825485665
2 Jessica Ennis Sheffield SF2 3ER 075668956665
3 Joe Bloggs Glasgow G3 2AZ 075659565666
I want a query to give me the results like this:
id | label
1 | Tom
1 | Daley
1 | London
1 | EC1 4EQ
1 | 075825485665
2 | Jessica
2 | Ennis
2 | Sheffied
and so on so forth.
Any suggestions please on how to do this.
回答1:
You can use the UNPIVOT function to turn the columns into rows:
select id, value
from yourtable
unpivot
(
value
for col in ([fName], [lName], [Address], [PostCode], [ContactNumber])
) unpiv
See SQL Fiddle with Demo.
The unpivot will require the datatype on all of the columns to be the same. So you might have to perform a cast
/convert
on any columns with different datatypes similar to this:
select id, value
from
(
select id, [fName], [lName], [Address], [PostCode],
cast([ContactNumber] as varchar(15)) [ContactNumber]
from yourtable
) src
unpivot
(
value
for col in ([fName], [lName], [Address], [PostCode], [ContactNumber])
) unpiv;
See SQL Fiddle with Demo.
Starting in SQL Server 2008, this can also be written using a CROSS APPLY
with a VALUES
:
select t.id,
c.value
from yourtable t
cross apply
(
values(fName),
(lName),
(Address),
(PostCode),
(cast(ContactNumber as varchar(15)))
) c (value)
See SQL Fiddle with Demo
回答2:
How about something like this:
SELECT
id, fName as label
FROM
table
UNION ALL
SELECT
id, lName
FROM
table
UNION ALL
SELECT
id, Address
FROM
table
...etc
来源:https://stackoverflow.com/questions/15359121/sql-query-to-get-the-resultset-in-two-columns-only