【问题标题】:insert using select distinct使用 select distinct 插入
【发布时间】:2013-01-09 13:17:37
【问题描述】:

假设我有 2 个表 t1 和 t2。

create table t1 
{
id int not null,
col1 int null,
col2 int null,
col3 int null
}

create table t2
{
id uniqueidentifier not null,
col1 int null,
col2 int null,
col3 int null
}

我想将下面的结果集插入到表 t2 中。

select distinct col1, col2, col3 from t1

如何使用查询来实现这一点?我尝试了以下语句,但我知道它在语法上是错误的。

insert into t2
select newid(), distinct col1, col2, col3 from t1

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:
    insert into t2
    select newid(),a.*
    from
    (Select distinct col1, col2, col3 from t1) a
    

    【讨论】:

      【解决方案2】:

      uniqueidentifier 字段如果是自动生成的,则可以省略。

      INSERT INTO t2 (col1, col2, col3)
      SELECT DISTINCT col1, col2, col3 FROM t1
      

      更多关于Using uniqueidentifier Data

      【讨论】:

      • 只有当它是自动生成的,如果它是明显的 int 或 null,ofc 不是
      【解决方案3】:

      这应该可以。

      INSERT INTO t2
      SELECT NEWID(), col1, col2, col3 
      FROM
      (
          SELECT DISTINCT col1, col2, col3 
          FROM t1
      )DT
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 2018-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多