请问该怎么写这条sql语句?

gqzhang 2005-04-13 03:55:09
表1:
aaa
-------
1
2
3

表2:
a b c
----------------
1 2 3
1 2 3
1 2 3
2 3 1
2 3 1
2 3 1

表2中三个字段a、b、c,其值都来源于表1的字段aaa

现想得出:

a中出现的次数 b中出现的次数 c中出现的次数
1 3 0 3
2 3 3 0
3 0 3 3

这条sql语句该怎么写呢?谢!
...全文
123 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gqzhang 2005-04-13
  • 打赏
  • 举报
回复
谢了!!
paoluo 2005-04-13
  • 打赏
  • 举报
回复
create table tb1 (aaa int)

create table tb2 (a int,b int ,c int)
insert into tb1 select 1 union select 2 union select 3 union select 4 union select 5

insert tb2
select 1 , 2 , 3 union all
select 1 , 2 , 3 union all
select 1 , 2 , 3 union all
select 2 , 3 , 1 union all
select 2 , 3 , 1 union all
select 2 , 3 , 1

Select * from (
select a.aaa,
sum(case when a.aaa=b.a then 1 else 0 end) as a中出现的次数,
sum(case when a.aaa=b.b then 1 else 0 end) as b中出现的次数,
sum(case when a.aaa=b.c then 1 else 0 end) as c中出现的次数
from tb1 a,tb2 b group by a.aaa
) A
Where a中出现的次数<>0 Or b中出现的次数<>0 Or c中出现的次数<>0


drop table tb1,tb2
gqzhang 2005-04-13
  • 打赏
  • 举报
回复
请容许我再问:

如果表1当中字段aaa
aaa
-----------
1
2
3
4
5

其中4、5在表b中未曾出现,如果按照上述的做法,就会出现

4 0 0 0
5 0 0 0

请问如何能过滤掉这种情况呢?
gqzhang 2005-04-13
  • 打赏
  • 举报
回复
谢谢!很直接、详细!
remote_peng 2005-04-13
  • 打赏
  • 举报
回复
create table tb1 (aaa int)

create table tb2 (a int,b int ,c int)
insert into tb1 select 1 union select 2 union select 3

insert tb2
select 1 , 2 , 3 union all
select 1 , 2 , 3 union all
select 1 , 2 , 3 union all
select 2 , 3 , 1 union all
select 2 , 3 , 1 union all
select 2 , 3 , 1

select a.aaa,
sum(case when a.aaa=b.a then 1 else 0 end) as a中出现的次数,
sum(case when a.aaa=b.b then 1 else 0 end) as b中出现的次数,
sum(case when a.aaa=b.c then 1 else 0 end) as c中出现的次数
from tb1 a,tb2 b group by a.aaa


drop table tb1,tb2
xiaomeixiang 2005-04-13
  • 打赏
  • 举报
回复

declare @tb1 table(aaa int)
declare @tb2 table(a int,b int ,c int)
insert @tb1 values(1)
insert @tb1 values(2)
insert @tb1 values(3)

insert @tb2 values( 1 , 2 , 3)
insert @tb2 values( 1 , 2 , 3)
insert @tb2 values( 1 , 2 , 3)
insert @tb2 values( 2 , 3 , 1)
insert @tb2 values( 2 , 3 , 1)
insert @tb2 values( 2 , 3 , 1)

select a.aaa,sum(case when a.aaa=b.a then 1 else 0 end) as a中出现的次数,sum(case when a.aaa=b.b then 1 else 0 end) as b中出现的次数,sum(case when a.aaa=b.c then 1 else 0 end) as c中出现的次数 from @tb1 a,@tb2 b group by a.aaa

34,591

社区成员

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

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