从行获取唯一值 - SQL Server

时间:2018-02-05 04:51:32

标签: sql sql-server

我有这样的列:

col1 | col2 | col3 | col4 | col5 | col6 |
-----+------+------+------+------+------+
  a  |  b   |  c   |   a  |   c  |   c

我正在尝试在自我PER行的列中获取唯一值。

理想情况下,我希望返回a,b,c

我尝试使用PIVOT并应用DISTINCT,但这并不顺利,因为我无法在问题中显示其他列。

那么还有另一种方法可以获得这个吗?

提前致谢

4 个答案:

答案 0 :(得分:1)

这就是你要找的......?

IF OBJECT_ID('tempdb..#Pivot_data')IS NOT NULL
DROP TABLE #Pivot_data

IF OBJECT_ID('tempdb..#tab')IS NOT NULL
DROP TABLE #tab


select * into #tab from
(select 'a'AS COL1,'b'AS COL2,'c'AS COL3,'a'AS COL4,'c'AS COL5,'c' COL6)AS A

DECLARE @Columns nvarchar(max) ,@QUERY NVARCHAR(MAX)

;WITH CTE AS (
SELECT COLUMNSS,COL_VALUES,ROW_NUMBER()OVER(PARTITION BY COL_VALUES ORDER BY (SELECT 1))RN FROM (
SELECT * FROM #tab
)AS A
UNPIVOT(COL_VALUES FOR COLUMNSS IN([col1],[col2],[col3],[col4],[col5],[col6])) AS B
) 

,FINAL_Result as (select COLUMNSS,COL_VALUES from CTE where RN=1)

SELECT * INTO #Pivot_data FROM FINAL_Result

SET @Columns= (SELECT STUFF((SELECT ',['+COLUMNSS+']' FROM #Pivot_data FOR XML PATH('')),1,1,''))


SET @QUERY=N'SELECT * FROM (
SELECT * FROM #Pivot_data
) AS A
PIVOT (MAX(COL_VALUES)FOR COLUMNSS IN('+@Columns+'))
AS B'

PRINT @QUERY
EXEC (@QUERY)

逻辑: 从给定的表中我做了 unpivot 并根据列值生成了一个Row_number(),并且只考虑了 Row_num = 1 ,即Distinct列值。最后,我转发了结果数据。

答案 1 :(得分:0)

似乎CROSS APPLY可以在这里工作

select a.Col from table t
cross apply (
    values (t.Col1), (t.Col2), (t.Col3),
           (t.Col4), (t.Col5), (t.Col6)
)a(Col) 
group by a.Col

AND ,以您自己的方式执行PIVOT

答案 2 :(得分:0)

试试此代码

IF OBJECT_ID('tempdb..#Temptab')IS NOT NULL
DROP TABLE #Temptab

;With cte(col1 , col2 , col3 , col4 , col5 , col6 )
AS
(
SELECT  'a'  ,  'b'   ,  'c'   ,   'a'  ,   'c'  ,   'c'
)
SELECT DISTINCT AllColumn 
INTO #Temptab FROM cte
CROSS APPLY ( VALUES (col1),( col2) , (col3) , (col4) , (col5) , (col6)
) AS A (AllColumn)


DECLARE @SqlQuery nvarchar(max)
       ,@Sql nvarchar(max)

SELECT @SqlQuery='SELECT DISTINCT  '+STUFF((SELECT ', '+ReqColumn FROM
(
SELECT ''''+AllColumn +'''' +' AS Col'+ CAST(Seq AS VARCHAR(2)) As ReqColumn
FROm
(
SELECT ROW_NUMBER()OVER(Order by AllColumn) AS Seq,AllColumn FROM #Temptab
)dt 
)dte  FOR XML PATH ('')),1,1,'') +' From #Temptab'



 PRINT @SqlQuery
 EXEC(@SqlQuery)

结果

 Col1   Col2    Col3
 ----------------------
  a      b        c

答案 3 :(得分:0)

您可以先union所有列获取唯一值,然后在MySql中使用 GROUP_CONCAT()函数,或者如果您的数据库是Oracle,则使用 list_agg()功能:

请尝试以下SQL:

select GROUP_CONCAT(col1 SEPARATOR ', ') from (
select '1' as 'serial', col1 from pivot
union
select '1' as 'serial',col2 from pivot
union
select '1' as 'serial',col3 from pivot
union
select '1' as 'serial',col4 from pivot
union
select '1' as 'serial',col5 from pivot
union
select '1' as 'serial' ,col6 from pivot
)derived
GROUP BY serial;

输出:

Output

注意:我已在查询中创建“序列”列来执行分组操作。如果您有,可以在group by子句中使用您的标识符字段。