SQL query to get the resultset in two columns only

。_饼干妹妹 提交于 2019-12-24 14:34:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!