更新表中的列

时间:2016-11-09 11:25:08

标签: sql sql-server tsql

所有

我尝试使用表格中的数据更新表格中的C_NEW列,但不确定从哪里开始。我希望底层解释有所帮助。

C1      | C2      | C3      | C4         | C_NEW
-------- --------- --------- ------------ -------
1@a.com | e@a.com | e@a.com | 1@a.com    |
1@a.com | e@a.com | 4@b.com | 12@f.com   |
1@a.com | e@a.com | 5@b.com | 123@k.com  |
4@b.com | b@a.com | 4@b.com | ab@123.com |
4@b.com | b@a.com | d@a.com | abc@12.com |
2@c.com | 3@c.com | b@1.com | a12@ff.com |

电子邮件需要通过C1和C2的组合发送给C1中的用户,因此三个单独的电子邮件应发送到1 @ a.com,4 @ b.com和2@c.com

复制到不在C1或C2的C3中的用户,所以在C_NEW列中我想要(4@b.com; 5@b.com)填写前三行和(d @ a。 com)应填写第4行和第5行,(b@1.com)应填写C_NEW列的最后一行。

还需要复制不在C1中的C4列中的用户。所以更新栏C_NEW应该有(4@b.com; 5@b.com; 12@f.com; 123@k.com)填写前三行和(d@a.com; ab @ 123。 com; abc@12.com)应填写第4行和第5行,并且(b@1.com; a12@ff.com)应填写C_New栏的最后一行。

根据以上数据,我应该有三份报告......

Report A: 1@a.com
Email to:
Copy to: 4@b.com; 5@b.com; 12@f.com; 123@k.com


Report B:
Email to: 4@b.com
Copy to: d@a.com; ab@123.com; abc@12.com

Report C:
Email to: 2@c.com
Copy to: b@1.com; a12@ff.com

表格的最终结果应该是这样的

C1      | C2      | C3      | C4         | C_NEW
-------- --------- --------- ------------ -------
1@a.com | e@a.com | e@a.com | 1@a.com    | 4@b.com; 5@b.com; 12@f.com; 123@k.com
1@a.com | e@a.com | 4@b.com | 12@f.com   | 4@b.com; 5@b.com; 12@f.com; 123@k.com
1@a.com | e@a.com | 5@b.com | 123@k.com  | 4@b.com; 5@b.com; 12@f.com; 123@k.com
4@b.com | b@a.com | 4@b.com | ab@123.com | d@a.com; ab@123.com; abc@12.com
4@b.com | b@a.com | d@a.com | abc@12.com | d@a.com; ab@123.com; abc@12.com
2@c.com | 3@c.com | b@1.com | a12@ff.com | b@1.com; a12@ff.com

1 个答案:

答案 0 :(得分:1)

您可以通过select语句更新现有数据。

在此您根据条件选择所有C3和C4并执行UNION。您需要在此列表中查看XML PATH并构建C_NEW列。

UPDATE [Table]
    SET C_NEW = SelectTable.C_NEW
FROM
( 
    SELECT [Table].c1, [Table].c2, c3, c4, SUBSTRING(t2.C_NEW , 2, LEN(t2.C_NEW)) AS C_NEW
    FROM dbo.[Table]
    LEFT JOIN (
    SELECT C1, C2, (
        (SELECT ', ' + C3 AS [text()]  FROM (
            SELECT C1, c2, C3 FROM [Table]
            WHERE C3 <> C1 AND C3 <> C2 AND C1 = t.C1 AND C2 = t.C2
            UNION 
            SELECT C1, c2, C4 FROM [Table]
            WHERE C4 <> C1 AND C1 = t.C1 AND C2 = t.C2
        ) AS t3 For XML PATH (''))
    )
    AS C_NEW
    FROM [Table] AS t
    GROUP BY C1, C2, t.C_NEW
    ) AS t2 ON t2.C1 = [Table].C1 AND t2.C2 = [Table].C2
) AS SelectTable
WHERE [Table].C1 = SelectTable.C1 
    AND [Table].C2 = SelectTable.C2 
    AND [Table].C3 = SelectTable.C3
    AND [Table].C4 = SelectTable.C4