SQL Query将不同的列数据合并为一个

时间:2013-10-19 08:00:06

标签: .net sql sql-server sql-server-2008-r2

我想将三个不同列的名称 ProcessFalseRedirect,ProcessTrueRedirect,GeneralRedirectToPP 合并到一个名为 PPID 的列中。

我正在使用的查询是

select ProcessFalseRedirect,ProcessTrueRedirect,GeneralRedirectToPP from IVR_PPMaster

给出了以下结果,

enter image description here

我希望我的输出像这样,

PPID
---------
PP-01
PP-02
PP-03
PP-04
PP-04A
PP-04B
PP-05

等等。

我想要一个忽略空白行和空白单元格的查询。

请帮忙。

4 个答案:

答案 0 :(得分:4)

UNION可以帮助您。

select ProcessFalseRedirect PPID from IVR_PPMaster
union
select ProcessTrueRedirect from IVR_PPMaster
union
select GeneralRedirectToPP from IVR_PPMaster

要按升序获取数据,请使用以下命令:

select PPID from
(
  select ProcessFalseRedirect PPID from IVR_PPMaster
  union
  select ProcessTrueRedirect from IVR_PPMaster
  union
  select GeneralRedirectToPP from IVR_PPMaster
) p
order by PPID

请注意,UNIONUNION ALL之间存在差异。

答案 1 :(得分:1)

试试这个:

(SELECT ProcessFalseRedirect PPID FROM IVR_PPMaster WHERE ProcessFalseRedirect IS NOT NULL
UNION ALL
SELECT ProcessTrueRedirect FROM IVR_PPMaster WHERE ProcessTrueRedirect IS NOT NULL
UNION ALL
SELECT GeneralRedirectToPP FROM IVR_PPMaster WHERE GeneralRedirectToPP IS NOT NULL)
ORDER BY ProcessFalseRedirect

答案 2 :(得分:1)

请这样做

SELECT ProcessFalseRedirect FROM IVR_PPMaster where ProcessFalseRedirect<>''
UNION
SELECT ProcessTrueRedirect from IVR_PPMaster where ProcessTrueRedirect<>'' 
UNION 
SELECT GeneralRedirectionTopp from IVR_PPMaster where GeneralRedirectionTopp<>''

答案 3 :(得分:1)

对于Sql Server 2008 +:

SELECT PPID
FROM IVR_PPMaster
CROSS APPLY (VALUES (ProcessFalseRedirect),
                    (ProcessTrueRedirect),
                    (GeneralRedirectToPP) ) AS Lines(PPID)
ORDER BY PPID

可以在此处找到解决方案说明:Table Value Constructors in SQL Server 2008