3表关联统计,求sql存储过程或语句

makoshen 2015-11-17 05:38:16
集团在全国各地有多家子公司,现在要统计员工最多的地区排列,求高手指点

省份表 【sf】
省份ID 省份名称

sfid sfname
1 北京
2 上海
3 广州
4 天津
.....


公司分布表 【gs】
公司ID 公司名称 公司归属省份ID

gsid gsname sfid
1 北京1公司 1
2 北京2公司 1
3 上海1公司 2
4 广州1公司 3
5 北京3公司 1


员工表 【yg】
员工ID 员工姓名 归属公司ID

ygID ygName gsid
1 张1 1
2 张2 2
3 张3 1
4 张4 5
5 张5 3
6 张6 4



求SQL 得到员工统计结果为:北京4个员工 上海1个员工 天津1个员工

北京地区(4)
上海地区(1)
天津地区(1)
...全文
127 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
knight_hf 2015-11-18
  • 打赏
  • 举报
回复
引用 2 楼 makoshen 的回复:
[quote=引用 1 楼 shoppo0505 的回复:] with sf(sfid, sfname) as ( select 1, '北京' union all select 2, '上海' union all select 3, '广州' union all select 4, '天津' ) , gs(gsid, gsname, sfid) as ( select 1, ' 北京1公司', 1 union all select 2, ' 北京2公司', 1 union all select 3, '上海1公司 ', 2 union all select 4, '广州1公司 ', 3 union all select 5, '北京3公司 ', 1 ) , yg (ygID, ygName, gsid) as ( select 1, '张1', 1 union all select 2, '张2', 2 union all select 3, '张3', 1 union all select 4, '张4', 5 union all select 5, '张5', 3 union all select 6, '张6', 4 ) select sf.sfname, count(yg.ygID) from sf inner join gs on gs.sfid = sf.sfid inner join yg on yg.gsid = gs.gsid group by sf.sfname
现在有个特殊的情况 就是员工在2个公司都有员工信息登记 员工ID号不一样 但是是同一人 只能算一个人 这样的情况怎么统计 亲[/quote] 至少要有一个能够判断是一个员工的依据才能统计吧。
shoppo0505 2015-11-17
  • 打赏
  • 举报
回复
数据库最基本的数据准确性,唯一性要求都不能做到,我也不知道怎么解决了。
makoshen 2015-11-17
  • 打赏
  • 举报
回复
引用 1 楼 shoppo0505 的回复:
with sf(sfid, sfname) as ( select 1, '北京' union all select 2, '上海' union all select 3, '广州' union all select 4, '天津' ) , gs(gsid, gsname, sfid) as ( select 1, ' 北京1公司', 1 union all select 2, ' 北京2公司', 1 union all select 3, '上海1公司 ', 2 union all select 4, '广州1公司 ', 3 union all select 5, '北京3公司 ', 1 ) , yg (ygID, ygName, gsid) as ( select 1, '张1', 1 union all select 2, '张2', 2 union all select 3, '张3', 1 union all select 4, '张4', 5 union all select 5, '张5', 3 union all select 6, '张6', 4 ) select sf.sfname, count(yg.ygID) from sf inner join gs on gs.sfid = sf.sfid inner join yg on yg.gsid = gs.gsid group by sf.sfname
现在有个特殊的情况 就是员工在2个公司都有员工信息登记 员工ID号不一样 但是是同一人 只能算一个人 这样的情况怎么统计 亲
shoppo0505 2015-11-17
  • 打赏
  • 举报
回复
with sf(sfid, sfname) as ( select 1, '北京' union all select 2, '上海' union all select 3, '广州' union all select 4, '天津' ) , gs(gsid, gsname, sfid) as ( select 1, ' 北京1公司', 1 union all select 2, ' 北京2公司', 1 union all select 3, '上海1公司 ', 2 union all select 4, '广州1公司 ', 3 union all select 5, '北京3公司 ', 1 ) , yg (ygID, ygName, gsid) as ( select 1, '张1', 1 union all select 2, '张2', 2 union all select 3, '张3', 1 union all select 4, '张4', 5 union all select 5, '张5', 3 union all select 6, '张6', 4 ) select sf.sfname, count(yg.ygID) from sf inner join gs on gs.sfid = sf.sfid inner join yg on yg.gsid = gs.gsid group by sf.sfname

34,576

社区成员

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

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