简体   繁体   English

选择多个值作为一列,而不是每个值的列,SQL Server

[英]Select many values as one column, not a column for each value, SQL Server

If you do this query in SQL Server it will give you 15 different columns- one for each postcode. 如果在SQL Server中执行此查询,它将为您提供15个不同的列 - 每个邮政编码一个。

SELECT 
    'CB89RX', 'CB259BL', 'CB19BF', 'CB245HS', 'CB30AP', 'CB12LJ', 
    'CB21RB', 'CB28PX', 'CB28PE', 'CB250HX', 'CB231HN', 'CB58TD', 
    'CB246AY', 'CB42QT', 'CB249JA' AS A

What I want is 1 column that contains all 15 values. 我想要的是包含所有15个值的1列。 How can I do this? 我怎样才能做到这一点?

You can try using UNPIVOT 您可以尝试使用UNPIVOT

select u.postcode
    from tablename
    unpivot
    (
      postcode
      for val in (CB89RX, CB259BL, CB19BF, CB245HS, CB30AP, CB12LJ, CB21RB, CB28PX, CB28PE, CB250HX, CB231HN, CB58TD, CB246AY, CB42QT, CB249JA)
    ) u;

I would like to use From .... VALUES 我想使用From .... VALUES

Select 
    val
From 
  (
  VALUES
    ('CB89RX'), 
    ('CB259BL'), 
    ....
  ) AS T (val)

sqlfiddle sqlfiddle

You can use union : 你可以使用union:

SELECT 'CB89RX' as PostalCode
Union
Select  'CB19BF'  as PostalCode 
Union 
Select 'CB245HS' as PostalCode 
Union 
... 

Try this to avoid repetitive use of as . 试试这个以避免重复使用as

SELECT   'CB89RX'  as A
   union 
   select  'CB259BL' 
   union 
   select 'CB19BF' 
   union 
   select 'CB245HS'
   union 
   select 'CB30AP'
   union 
   select    'CB12LJ'
   union 
   select    'CB21RB'
   union 
   select    'CB28PX'   
   union 
   select    'CB28PE'
   union 
   select    'CB250HX'
   union 
   select 'CB231HN'
   union 
   select 'CB58TD'
   union 
   select 'CB246AY'
   union 
   select 'CB42QT'
   union 
   select 'CB249JA' 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL Server 2008 R2,为另一列的每个不同值选择一个列的一个值 - SQL server 2008 R2, select one value of a column for each distinct value of another column 选择一列的值到一行 - SQL Server - Select values of a column into one row - SQL Server SQL 按一列选择唯一值,按另一列选择最新值 - SQL Select unique values by one column with the latest value by another column SQL根据另一列中的值从一列中选择值 - SQL select value from one column based on values in another column 在标准SQL中,如何选择行,以便对于一列中的每个唯一值,另一列中的所有值都是指定值? - In standard SQL, how do I select rows such that for each unique value in one column, all of the values in another column are a specified value? Oracle SQL在一个查询中选择多列不同的值,并根据不同的值对每一列进行分页 - Oracle SQL select multiple columns distinct values in one query with pagination requirement for each column based on distinct value 从“ SQL Server”列中递增选择值,并将每个值设置为等于一个变量 - Incrementally select values from SQL Server column, and set each value equal to a variable SQL 选择一个不为零的列值,如果有多个值则选择最后一个 - SQL select a column value that is not zero and if there are multiple values to select the last one sql server-一对多查询到一列 - sql server - query one to many into one column SQL Server-从一列中选择值对 - SQL Server - Select pairs of values from one column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM