简单的count

sunhood 2008-02-20 06:08:06
有3个表都有编号列,统计每个表中同一编号的记录数。
大致如下:


表1 表2 表3
code code code
------- ----------- -----------
ABCD ABCD
ABCD ABCD
ABCD
ABCD


希望得到如下结果

code 表1(此处用a1,a2标识也可) 表2 表3
------- ----------- ----------- -------
ABCD 4 2 0
...全文
81 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2008-02-20
  • 打赏
  • 举报
回复
改改9楼的
select 
code,
[表1]=sum(case when TName='表1' then 1 else 0 end),
[表2]=sum(case when TName='表2' then 1 else 0 end),
[表3]=sum(case when TName='表3' then 1 else 0 end)

from
( select code ,'表1' as TName from 表1
union
select code ,'表2'from 表2
union
select code ,'表3'from 表3 )T
group by code
-狙击手- 2008-02-20
  • 打赏
  • 举报
回复
elect 
code,
[表1]=sum(case when TName='表1' then 1 else 0 end),
[表2]=sum(case when TName='表2' then 1 else 0 end),
[表3]=sum(case when TName='表3' then 1 else 0 end)

from
( select code ,'表1' as TName from 表1
union
select code ,'表2'from 表2
union
select code ,'表3'from 表3 )T
group by code
cxmcxm 2008-02-20
  • 打赏
  • 举报
回复
select code=case when a.code is not null then a.code else 
case when b.code is not null then b.code else c.code end end,
a1=isnull(a.a1,0),a2=isnull(b.a2,0),a3=isnull(c.a3,0)

from
(select code,count(*) a1 from 表1 group by code) a full join
(select code,count(*) a2 from 表2 group by code) b on a.code=b.code full join
(select code,count(*) a3 from 表3 group by code) c on a.code=c.code and b.code=c.code
中国风 2008-02-20
  • 打赏
  • 举报
回复

select
code,
[表1]=sum(case when TName='表1' then 1 else 0 end),
[表2]=sum(case when TName='表2' then 1 else 0 end),
[表3]=sum(case when TName='表3' then 1 else 0 end)

from
( select code ,'表1' as TName from 表1
union
select code ,'表2'from 表2
union
select code ,'表3'from 表3 )T
where
code='abcd'
ruihuahan 2008-02-20
  • 打赏
  • 举报
回复
select ....
from (select code, count(*) from table1) t1
inner join (select code, count(*) from table2) t2
on t1.code=t2.code
inner join (select code, count(*) from table3) t3
on t2.code=t3.code
sunhood 2008-02-20
  • 打赏
  • 举报
回复
有没有更简便的写法??
liangCK 2008-02-20
  • 打赏
  • 举报
回复
就3楼的去写吧.
sunhood 2008-02-20
  • 打赏
  • 举报
回复
用left outer join或union 我可以写,但是尽量不想用left outer 或者union,该怎么写?
sunhood 2008-02-20
  • 打赏
  • 举报
回复
code列中会有很多编码比如:ABCD, AAAA,BBBB.......该怎么count?
liangCK 2008-02-20
  • 打赏
  • 举报
回复
select code
,表1=(select count(code) from 表1 where code=a.code)
,表2=(select count(code) from 表2 where code=a.code)
,表3=(select count(code) from 表3 where code=a.code)
from
(
select code from 表1
union
select code from 表2
union
select code from 表3
) a
wzy_love_sly 2008-02-20
  • 打赏
  • 举报
回复
select code='abcd',
a1=(select count(1) from 表1 where code='abcd'),
a2=(select count(1) from 表2 where code='abcd'),
a3=(select count(1) from 表3 where code='abcd')
wzjpsq 2008-02-20
  • 打赏
  • 举报
回复
left join

34,590

社区成员

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

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