SQL合并SQL表中的匹配行

时间:2016-04-21 19:22:28

标签: sql sql-server-2008

这是我的表架构

    public void connectClient(String user){
        try{
            host = clientSocket.getInetAddress();
            clientSocket = new Socket(host,port);
            new ClientHandler(clientSocket).run();
            String accepted = "Connection for host "+host+" accepted on port: "+clientSocket.getPort();
        }
        catch(Exception e){
            //sendMessage("Connection error: "+e);
            //serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect");
        }

    }

这是我的示例数据

config

我想更新Column2,如果column1值被重复,并且column2中的任何一行是空的,则空单元格将被非空单元格替换。

例如,上述样本数据的所需输出将为

Table1
{
Column1 nVarchar(Max),
Column2 nVarchar(Max)
}

2 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE Table1
SET Column2 =
    (SELECT t1.Column2 FROM Table1 t1
     WHERE t1.Column1 = Table1.Column1
     AND t1.Column2 IS NOT NULL)
WHERE Column2 IS NULL
AND EXISTS (
    SELECT 'OTHER'
    FROM Table1 t1
    WHERE t1.Column1 = Table1.Column1
    and t1.Column2 IS NOT NULL)

答案 1 :(得分:0)

以下内容将使用最大值Ignoring nulls或空字符串进行更新。

如果只有一种不同的可能性,那么当然将是所选择的那种。

;WITH T AS 
(
SELECT *, 
       MAX(NULLIF(Column2,'')) OVER (PARTITION BY Column1) AS C2
FROM YourTable
)
UPDATE T
SET Column2 = C2
WHERE Column2 IS NULL OR Column2 = '';