如何将两行合并为一个MSSQL

时间:2017-01-23 08:27:31

标签: sql-server

我有一个MSSQL表,我想将两行的名称合并为一个。名字是较小的值,第二名称的值较大。如果两个值相同,则只组合第一个和第二个名称。

每一行包含2个名称first1和First2用空格分隔(薪水或First1低于薪水或First2

目前,结果是:

enter image description here

我希望结果像

Buchanan Suyama
Peacock Callahan
Dodsworth King
Leverling Davolio
Fuller

3 个答案:

答案 0 :(得分:2)

    CREATE TABLE ABC 
(
COLUMN_1 VARCHAR(10),
PRICE INT
)
INSERT INTO ABC VALUES
('A',100),
('B',200),
('C',300),
('D',400),
('E',500),
('F',600),
('G',700),
('H',800),
('I',900)

SELECT Concat(COLUMN_1, ' ', t) AS ADDEDVALUE 
    FROM   (SELECT *,
                   Lead(COLUMN_1, 1)OVER (ORDER BY PRICE) AS t
            FROM   ABC)A 

OUTPUT
ADDEDVALUE
A B
B C
C D
D E
E F
F G
G H
H I
I

答案 1 :(得分:2)

Chanukaya的答案很棒,旧版本使用此

SELECT Min(title),
       case when Min(title) = Max(title) then '' else Max(title) end
FROM   (SELECT *,
               ( Row_number() OVER( ORDER BY salary) - 1 ) / 2 + 1 as Grp
        FROM   yourtable) a 
Group By Grp

答案 2 :(得分:1)

你也可以,

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY Salary) AS RowId,
        LastName ,
        Salary
    FROM 
        Employees   
)

SELECT
    currentRow.LastName + ' ' + nextRow.LastName
FROM 
    CTE currentRow LEFT JOIN 
    CTE nextRow ON currentRow.RowId = nextRow.RowId - 1
WHERE
    currentRow.RowId % 2 <> 0