SQL查询以获取基于值的特定行

时间:2013-03-13 09:35:24

标签: sql

鉴于此表:

SubstationNo SubstationType
----------------------------
     1411             1566
     1411             135
     1422             1411
     1433             1433

如何将两个不同列中的不同值作为由一行中的|符号分隔的值

需要的结果是

1411|1422|1433|1566|135|1433

5 个答案:

答案 0 :(得分:0)

这将使用与混合列的联合进行子选择。不确定您的RDBMS是否可用。

SELECT DISTINCT * FROM
(
  SELECT SubstationNo FROM table
  UNION
  SELECT SubstationType FROM table
)

答案 1 :(得分:0)

GROUP_CONCAT()函数将所有行连接为单个字符串。此处的查询将为两列提供所有唯一值

SELECT  GROUP_CONCAT(
    select distinct * from (SELECT column1
    FROM tablename
    UNION
    SELECT column2
    FROM tablename) SEPARATOR '|') AS rowValue
FROM  tablename

答案 2 :(得分:0)

  

如果您使用SQL Server,则可以执行此操作:

;WITH CTE
AS
(
  SELECT SubstationNo AS COL FROM Table1
  UNION
  SELECT SubstationType AS COL FROM Table1
)


SELECT DISTINCT 
STUFF((
     SELECT '|'+ CAST(COL AS VARCHAR(50)) 
     FROM CTE
     FOR XML PATH ('')),1,1,'')
FROM TABLE1

SQL FIDDLE DEMO

答案 3 :(得分:0)

如果你使用MySQL,你可以使用GROUP_CONCAT(),但比Ajo Koshy更容易。

每列一个GROUP_CONCAT,然后通过CONCAT()

将它们放在一起
SELECT 
CONCAT(GROUP_CONCAT(DISTINCT column1 SEPARATOR '|'), '|', GROUP_CONCAT(DISTINCT column2 SEPARATOR '|'))
FROM yourTable

这是manual entry for GROUP_CONCAT().

答案 4 :(得分:0)

如果您正在SQL SERVER尝试这些内容,请尝试以下内容..它会帮助您..

SELECT DISTINCT 
STUFF((
     SELECT '|'+ CAST(SubStation AS VARCHAR(50))
     FROM (SELECT DISTINCT SubstationNo SubStation
 FROM TableName
 UNION
 SELECT DISTINCT SubstationType as SubStation
 FROM TableName) res
     FOR XML PATH ('')),1,1,'') as SubStation
FROM TableName