SQL查询在重复键上插入和更新

时间:2016-04-18 08:02:24

标签: sql sql-server

我有一张桌子。 aTable有以下记录:

    +----+------+------------------+--------+
    | No | Name | Date(mm/dd/yyyy) | Salary | 
    +----+------+------------------+--------+
    | 1  | Ed   |    04/01/2016    | 1000   |
    | 2  | Tom  |    04/02/2016    | 1500   |
    +----+------+------------------+--------+

SQL Server查询如何将这些结果生成到其他表:

+----+------+------------------+--------+---+
| No | Name | Date(yyyy/mm/dd) | Salary | k |
+----+------+------------------+--------+---+
| 1  | Ed   |    04/01/2016    | 1000   | 0 |
| 2  | Tom  |    04/02/2016    | 1500   | 0 |
+----+------+------------------+--------+---+

并在重复密钥时更新。主键是No和Name

3 个答案:

答案 0 :(得分:1)

您希望在新表格中生成与您的表格完全相同的数据,只需使用新的列k,即" 0"无论如何?

SELECT *,0 AS k
INTO TheNewTable
FROM YourTable;

然后用

试试
SELECT * FROM TheNewTable;

但是 - 说实话 - 这似乎很奇怪......

答案 1 :(得分:0)

试试这个:

Insert into second_table_name(No, Name, Date, Salary, k) 
    select 
        No, Name, Date, Salary, 0 
    from aTable

答案 2 :(得分:0)

主键是UNIQUE,因此您无法复制它。或者你的逻辑键可能是其他组合,例如Name,Date,Salary,那么示例查询可能是这样的:

MERGE aNewTable as Target
USING 
(
    SELECT Name, Date, Salary, CASE WHEN Count(*) > 1 THEN 1 ELSE 0 END as K
    FROM aTable
    GROUP BY Name, Date, Salary
) as Source ON Source.Name=Target.Name AND Source.Date=Target.Date AND Source.Salary=Target.Salary
WHEN NOT MATCHED THEN
    INSERT (Name, Date, Salary, K)
    VALUES (Source.Name, Source.Date, Source.Salary, Source.K)
WHEN MATCHED THEN
    UPDATE 
    SET K = Source.K
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

或简单查看:

SELECT Name, Date, Salary, CASE WHEN Count(*) > 1 THEN 1 ELSE 0 END as K
FROM aTable
GROUP BY Name, Date, Salary