3-28学会的几句sql语句

本文介绍了三种实用的SQL技巧:如何使两张结构相同的表数据同步;如何查找表中某列的不重复记录及其出现次数;以及如何通过动态SQL将查询结果转换为特定格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   
   1.两张结构相同的表,使他们的数据同步
      
      create table #A(id int, y vachar(10))
      create table #B(id int, y varchar(10))
      
      insert into #A 
         select 1, 'a1'
         union
         select 2, 'a2'
      select * from #A
      
      insert into #B
         select 1, 'b1'
         union
         select 2, 'b2'
      select * from #B

      update #B set y=#A.y from #B,#A where #A.id=#B.id
      
      select * from #B
      
      drop table #A
      drop table #B

   2.对于一张表的一列,查找出不重复的记录

      create table #A(x int,y varchar(10))
      
      insert into #A 
         select 1, '张三'
         union  
         select 2, '张三'
         union
         select 3, '李四'

      select distinct y,count(y) [count] from #A group by y

      drop table #A

   3.将表A查询成下面的样子
表A

id    x
1    abc
2    xyz
3    abc
4    abc

B
abc  xyz
3     1  

   select * into #temp from( select
      1 id,    'abc' x
      union
      select 2,    'xyz'
       union
      select 3,    'abc'
      union
      select 4,    'abc'
      ) A

     select * from #temp
    declare @sql varchar(8000)
      set @sql = 'select '

    select @sql = @sql + ltrim(str(f2)) + ' ' + f1 + ', ' from 
   (
       select x f1, count(*) f2 from #temp group by x
    ) A


     set @sql =  substring(@sql, 1, len(@sql) - 1)

   select @sql

   exec( @sql )

   drop table #temp

      

转载于:https://www.cnblogs.com/QiuYun/archive/2007/03/28/691222.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值