增加一个表,怎么查询?

emilchan6k 2007-07-09 08:28:13
参考这个帖子,我试了半天也没弄出来

http://community.csdn.net/Expert/TopicView3.asp?id=5643256
现在我要增加一个表的关联
tableC
userID,userName
1 admin
2 test
3 test2


...全文
79 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
emilchan6k 2007-07-09
  • 打赏
  • 举报
回复
看来我对group by 理解得不透彻。。。。拜ls
hellowork 2007-07-09
  • 打赏
  • 举报
回复
if object_id('tbTest1') is not null
drop table tbTest1
if object_id('tbTest2') is not null
drop table tbTest2
if object_id('tbTestC') is not null
drop table tbTestC
GO
create table tbTest1(aid int,name varchar(10),modelsId int)
insert tbTest1
select 1,'发贴',1 union all
select 2,'回贴',1 union all
select 3,'消息',2 union all
select 4,'申请',3
create table tbTest2(userid int,aid int,action varchar(10),content varchar(10))
insert tbTest2
select 1, 1, 'add', 'fsfdsfsd' union all
select 1, 2, 'add', 'sdfsfasf' union all
select 2, 3, 'add', 'adfsfddf' union all
select 3, 3, 'add', 'adfssddf'
create table tbTestC(userid int,userName varchar(10))
insert tbTestC
select 1, 'admin' union all
select 2, 'test' union all
select 3, 'test2'

----汇总
declare @sql varchar(8000)
set @sql = 'select a.userid,c.userName'
select @sql = @sql + ',' + name + '=sum(case b.name when ''' + name + ''' then 1 else 0 end)'
from tbTest1 group by name
set @sql = @sql + ' from tbTest2 as a
left join tbTest1 as b on a.aid = b.aid
LEFT JOIN tbTestC as c on a.userid = c.userid
group by a.userid,c.userName'
EXEC(@sql)

----清除测试环境
drop table tbTest1,tbTest2,tbTestC


/*结果
userid userName 发贴 回贴 申请 消息
----------- ---------- ----------- ----------- ----------- -----------
1 admin 1 1 0 0
2 test 0 0 0 1
3 test2 0 0 0 1
*/
yaoshun1983 2007-07-09
  • 打赏
  • 举报
回复
建个视图吧。

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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