单个文本值,从所有行获取唯一值

时间:2013-05-15 02:43:13

标签: sql postgresql

假设我有这些行:

ROW 1 apple,watermelon,pineapple

ROW 2 apple,pineapple,orange

ROW 3 apple,blue berry

我想创建单个文本值,从所有行中获取唯一值。

我们如何使用查询?

预期结果:

apple,watermelon,pineapple,orange,blue berry

3 个答案:

答案 0 :(得分:2)

试试这个:

select array_agg(val) from (
  select distinct unnest(string_to_array(my_column, ',')) val from my_table) x

发生了什么:

  • string_to_array()使用指定的分隔符将字符串拆分为真正的数组
  • unnest()将数组转换为单独的行 - 每个元素一行
  • distinct删除重复的行
  • array_agg()将所有行合并为一个CSV字符串(通常您会使用group by子句,但此处不需要,因为只有一个组)

答案 1 :(得分:0)

您可以使用“关注”功能按“,

拆分行值
CREATE FUNCTION [dbo].[ConvertToTable]
    (
      @delimiter char(1),
      @string nvarchar(MAX)
    )
RETURNS @Values TABLE ( VALUE NVARCHAR(MAX) )
AS BEGIN
    SET @string = @string + @delimiter ;

    WITH    Nbrs_3 ( n ) AS ( SELECT   1 UNION SELECT   0 ) ,
            Nbrs_2 ( n ) AS ( SELECT   1 FROM     Nbrs_3 n1 CROSS JOIN Nbrs_3 n2 ) ,
            Nbrs_1 ( n ) AS ( SELECT   1 FROM     Nbrs_2 n1 CROSS JOIN Nbrs_2 n2 ) ,
            Nbrs_0 ( n ) AS ( SELECT   1 FROM     Nbrs_1 n1 CROSS JOIN Nbrs_1 n2 ) ,
            Nbrs ( n ) AS ( SELECT   1 FROM     Nbrs_0 n1 CROSS JOIN Nbrs_0 n2 )
       INSERT @Values ( [VALUE] )
        SELECT  SUBSTRING(@string, n + 1, CHARINDEX(@delimiter, @string, n + 1) - n - 1)
        FROM    ( SELECT    0 AS 'n' UNION ALL
                  SELECT TOP ( LEN(@string) - 1 ) ROW_NUMBER() OVER ( ORDER BY n ) AS 'n' FROM      Nbrs
                ) x
        WHERE   SUBSTRING(@string, n, 1) = @delimiter
                OR n = 0

    RETURN 
   END

并使用以下代码获取结果..

DECLARE @unique_value NVARCHAR(MAX)

WITH cte AS (
SELECT 1 AS id, 'apple,watermelon,pineaple' AS String
UNION
SELECT 2 ,'apple,pineaple,orange'
UNION
SELECT 3 ,'apple,blue berry'

)

SELECT @unique_value= COALESCE(@unique_value+',','')+[VALUE] FROM [cte]
CROSS APPLY [dbo].[ConvertToTable](',',[String]) AS CTT
GROUP BY [VALUE]

SELECT @unique_value

UPDATE :我没有注意到这是关于postgresql的。我给了MSSQL的答案,如果你可以在postgresql中做同样的事情。这种方法可以帮到你..

答案 2 :(得分:0)

试试这个:

SELECT ARRAY(SELECT distinct    regexp_split_to_table(myTable.columns, E',') AS split_columns FROM myTable);