2

我有一张桌子:

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 的。

我还尝试了一些使用 distinct 和 group by 的各种尝试,但没有任何工作。

非常感谢任何建议或方向!

4

2 回答 2

3

也许有一个子查询,它将所有四列成对GROUP BY连接起来,结果是 a:

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

于 2013-08-22T16:05:19.910 回答
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

于 2013-08-22T16:31:58.577 回答