将列转换为行的 SQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21287855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:51:11  来源:igfitidea点击:

SQL query to convert columns into rows

sqlsql-servertsql

提问by Happy

I have a table as shown below.My question is:How can I convert columns into rows? I'm using Microsoft SQL Server

我有一个如下所示的表格。我的问题是:如何将列转换为行?我正在使用 Microsoft SQL Server

   sip_RECno  user1     user2    user3     user4       

   1          ram       ravi     sam       raj

i need op like below

我需要像下面这样的操作

 user
 ram
 ravi
 sam
 raj

how to do it? thanks

怎么做?谢谢

回答by M.Ali

Your Data

您的数据

DECLARE @TABLE TABLE 
(sip_RECno INT,user1 VARCHAR(10),user2 VARCHAR(10)
,user3 VARCHAR(10),user4 VARCHAR(10))      

INSERT INTO @TABLE VALUES
(1,'ram','ravi','sam','raj')

Query

询问

;WITH CTE
AS
  (
  SELECT * FROM (
  SELECT user1 ,user2 ,user3 , user4 FROM @TABLE) T
  UNPIVOT ( Value FOR N IN (user1 ,user2 ,user3 , user4))P
  )
 SELECT Value AS Users
 FROM CTE

Result Set

结果集

╔═══════╗
║ Users ║
╠═══════╣
║ ram   ║
║ ravi  ║
║ sam   ║
║ raj   ║
╚═══════╝

回答by Kiril Rusev

You can simply UNPIVOT()

你可以简单地 UNPIVOT()

select [user] from table_name unpivot 
      (
       [user]
       for [userid] in ([user1], [user2], [user3], [user4]) 
      )unpvt

Demo

演示