数据更新,列可不可以"选"

blueshu 2003-05-08 07:50:44
我有表table1,结构如下
序号 姓名 身份
1 王 干部
2 李 干部
3 赵 工人
现有另一表table2,结构如下
干部  工人
2 1
要求根据table1,用一条sql语句生成table2
不知有没有这个可能
...全文
61 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
愉快的登山者 2003-05-08
  • 打赏
  • 举报
回复
select (count(*) from table1 where 身份='干部') 干部,
(count(*) from table1 where 身份='工人') 工人 into table2
select * from table2
CrazyFor 2003-05-08
  • 打赏
  • 举报
回复

select
sum(case when 身份='干部' then 1 else 0 end) 干部,
sum(case when 身份='工人' then 1 else 0 end) 工人
into table2 --如果TABLE2表还不存在加INTO子句,
from table1
yoki 2003-05-08
  • 打赏
  • 举报
回复
如果你的表中身份是固定的列,那么用happydreamer(偶很菜) 的,如果不确定就用我的:

declare @ table (序号 int, 姓名 varchar(20), 身份 varchar(50))
insert into @ values(1, '王', '干部')
insert into @ values(2, '李', '干部')
insert into @ values(3, '赵', '工人')
insert into @ values(4, '赵', '领导')

select count(身份) as 数量,身份 into temp from @ group by 身份

declare @sql varchar(8000)
set @sql = 'select '
select @sql = @sql + ',sum(case 身份 when '''+身份+''' then 数量 else 0 end) as '+身份
from (select distinct 身份 from temp) as a
select @sql='select '+right(@sql,len(@sql)-8)
select @sql = @sql+' from temp '
exec(@sql)

drop table temp
yoki 2003-05-08
  • 打赏
  • 举报
回复
declare @ table (序号 int, 姓名 varchar(20), 身份 varchar(50))
insert into @ values(1, '王', '干部')
insert into @ values(2, '李', '干部')
insert into @ values(3, '赵', '工人')
insert into @ values(4, '赵', '领导')

select count(身份) as 数量,身份 into temp from @ group by 身份

declare @sql varchar(8000)
set @sql = 'select 1 '
select @sql = @sql + ',sum(case 身份 when '''+身份+''' then 数量 else 0 end) as '+身份
from (select distinct 身份 from temp) as a
select @sql = @sql+' from temp '
exec(@sql)

drop table temp
happydreamer 2003-05-08
  • 打赏
  • 举报
回复
select sum(case 身份 when '干部' then 1 else 0 end) as 干部,
sum(case 身份 when '工人' then 1 else 0 end) as 工人
into table2
from table1
happydreamer 2003-05-08
  • 打赏
  • 举报
回复
select sum(case 身份 when '干部' then 1 else 0 end) as 干部,
sum(case 身份 when '工人' then 1 else 0 end) as 工人
into table2
from table1
blueshu 2003-05-08
  • 打赏
  • 举报
回复
各位我忘了,还要按条件更新啊
如table1的序号为单位
要按单位来更新怎么?
table2增加一单位字段
此时怎办?

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧