将不同列的结果输入到单个列中

时间:2013-08-22 15:56:58

标签: sql sql-server group-by distinct

我的桌子有:

col1     col2     ...     Plastname     Pfirstname     Clastname      Cfirstname
1        abc              Smith         John           Robinson       Bob
2        xyz              Smith         John           Jones          Michael
3        bda              Robinson      Bob            Smith          John

我想要的是一个不同名称的单一列表,例如:

col1
Smith, John
Robinson, Bob
Jones, Michael

我尝试过工会:

select distinct Plastname + ', ' + Pfirstname as name from table
union
select distinct Clastname + ', ' + Cfirstname as name from table

但是这并没有给我一个clastname和cfirstname。

我也曾尝试过各种各样的尝试,使用不同的分组,但没有任何工作。

非常感谢任何建议或指示!

2 个答案:

答案 0 :(得分:3)

可能使用子查询将所有四列作为成对进行连接,并在结果上进行GROUP BY

SELECT X.NAME FROM
(
    SELECT Plastname + ', ' + Pfirstname AS NAME
    FROM People
    UNION ALL
    SELECT Clastname + ', ' + Cfirstname AS NAME
    FROM People
) X
GROUP BY X.NAME
ORDER BY X.NAME

DEMO

甚至更容易:将UNION ALL替换为UNION,以消除重复:

SELECT Plastname + ', ' + Pfirstname AS NAME
FROM People
UNION 
SELECT Clastname + ', ' + Cfirstname AS NAME
FROM People

DEMO

答案 1 :(得分:0)

我检查了您的查询,但工作正常http://sqlfiddle.com/#!3/bac7f/4
但建议使用每行分为四列,分为两列,两列。

SQLServer2008上的示例+

SELECT DISTINCT o.lastname + ', ' + o.firstname AS name
FROM dbo.test142 t 
  CROSS APPLY(
              VALUES(Plastname, Pfirstname),
                    (Clastname, Cfirstname)
              ) o(lastname, firstname)

请参阅SQLFiddle

上的演示