我想仅在列值不相同时才选择某些列。列值可能会有所不同,我不知道它们可能具有的确切值。我也有一些列,我想总是选择,无论有什么价值。
我的输出数据目前如下:
Column A Column B Column C Column D Column E Column F
1 BB 777 NULL Louis 0
2 BB 777 NULL Peter 0
3 BB 777 NULL Mary 0
4 BB 777 NULL Paul 0
我总是希望输出从A列返回数据,但只有在值不相同时才返回B,C,D,E和F列。在这种情况下,我只希望输出数据返回A和E列:
Column A Column E
1 Louis
2 Peter
3 Mary
4 Paul
列A,B和C来自Table_X,列D,E和F来自Table_Y。
这是我到目前为止所写的内容,我只管理了选择部分:
SELECT Column A
Column B
Column C
Y.Column D
Y.Column E
Y.Column F
FROM Table_X
INNER JOIN Table_Y AS Y ON Table_X.Id = Y.Table_XId
我浏览过并发现了一些类似于我的问题的其他帖子,但它们与我想要的并不匹配,不想选择相同的值,无论价值是多少,即: MySQL - SELECTING COLUMNS ONLY IF THEY HAVE VALUES
非常感谢!
答案 0 :(得分:0)
这是一种可能的解决方案。
计算每列的不同值。使用UNPIVOT,转换行中的列并仅选择具有多个值的行。将列名称放入一个字符串并执行一个dinamic查询。
create table #t (a int, b varchar(max), c varchar(max), d varchar(max), e varchar(max), f varchar(max))
insert into #t
select 1,'bb','777',null,'louis','0' union
select 2,'bb','777',null,'peter','0' union
select 3,'bb','777',null,'mary','0' union
select 4,'bb','777',null,'paul','0'
declare @columnsToSelect varchar(max)
select @columnsToSelect = replace(replace(( select columnName
from(
select b = count(distinct b),
c = count(distinct c),
d = count(distinct d),
e = count(distinct e),
f = count(distinct f)
from #t) t
unpivot (number_of for columnName IN(b,c,d,e,f)) as unp
where number_of > 1
for xml auto),'<unp columnName="',''),'"/>',',')
if @columnsToSelect is not null begin
select @columnsToSelect = left(@columnsToSelect, len(@columnsToSelect)-1)
select @columnsToSelect
exec('select a,'+@columnsToSelect+' from #t')
end
drop table #t
答案 1 :(得分:0)
您可以尝试以下查询来获取所需的输出
DECLARE @SQL varchar(max)
DECLARE @ColumnBCount int
DECLARE @ColumnCCount int
DECLARE @ColumnDCount int
DECLARE @ColumnECount int
DECLARE @ColumnFCount int
SELECT @ColumnBCount = COUNT(DISTINCT [ColumnB])
,@ColumnCCount= COUNT(DISTINCT [ColumnC])
,@ColumnDCount= COUNT(DISTINCT [ColumnD])
,@ColumnECount= COUNT(DISTINCT [ColumnE])
,@ColumnFCount=COUNT(DISTINCT [ColumnF])
FROM Table_X AS X
INNER JOIN Table_Y AS Y ON X.Id = Y.Table_XId
SELECT @SQL= 'SELECT ColumnA'
+ CASE WHEN @ColumnBCount>1 THEN ',ColumnB' ELSE '' END
+CASE WHEN @ColumnCCount>1 THEN ',ColumnC' ELSE '' END
+CASE WHEN @ColumnDCount>1 THEN ',ColumnD' ELSE '' END
+ CASE WHEN @ColumnECount>1 THEN ',ColumnE' ELSE '' END
+CASE WHEN @ColumnFCount>1 THEN ',ColumnF' ELSE '' END
+' FROM Table_X AS X
INNER JOIN Table_Y AS Y ON X.Id = Y.Table_XId'
EXEC (@SQL)