如何连接来自同一表的两列并在SQL中格式化新列

时间:2019-10-19 19:32:39

标签: sql sql-server

我对SQL还是很陌生,她试图将同一张表中的两列连接起来并格式化结果。

到目前为止,我的代码是:

Select LastName + FirstName as FullName
from Customers
order by FullName

我要加入的列是LastNameFirstName

结果的格式应为: 全名,格式如下:

  

Doe,约翰

该代码仅应显示姓氏为M-Z的结果。任何帮助是极大的赞赏。我已附上下面的屏幕截图,以供参考。

https://i.stack.imgur.com/k6qpE.png

4 个答案:

答案 0 :(得分:2)

您可以使用计算列:

CREATE TABLE Customers(LastName NVARCHAR(100), FirstName NVARCHAR(100));
INSERT INTO Customers VALUES ('Doe', 'John'), ('Nagata', 'Naomi');

ALTER TABLE Customers ADD FullName AS (CONCAT(LastName, ', ', FirstName));

Select *
from Customers
where LastName LIKE '[M-Z]%'
order by FullName;

db<>fiddle demo

答案 1 :(得分:1)

Select LastName +', '+ FirstName as FullName
from Customers
order by FullName

答案 2 :(得分:0)

尝试一下

Select * from (select Firstname + ' ' + Lastname as Fullname from Students) a order by a.Fullname

答案 3 :(得分:0)

尝试一下:

select 
    [LastName]+ ', '+[FirstName] as FullName
    from [db]
    where left([LastName],1) in (
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z')

    order by FullName

    ;