费用分摊问题的SQL语句

liujiaqiang 2005-04-15 06:43:22

有宿舍表:
RS_Room : 字段为 RoomCode , EMoney
001 600
002 500
有床位表:
RS_Bed : 字段为 BedCode RoomCode EmpCode Flag(1:表示入住 0:表示空缺)
001-01 001 Em001 1
001-02 001 Em002 1
001-03 001 Em003 1
001-04 001 0
002-01 002 0
002-02 002 Em004 1
002-03 002 0
002-04 002 0


现在如何算出Em001这位员工的住宿分摊的住宿费用为:200元 ?
...全文
394 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liujiaqiang 2005-04-16
  • 打赏
  • 举报
回复
paoluo(一天到晚游泳的鱼),谢谢你的帮助。
paoluo 2005-04-15
  • 打赏
  • 举报
回复
如果只查询Em001的:

Select
EmpCode,
(Select EMoney from RS_Room Where RoomCode=A.RoomCode)/(Select Count(*) from RS_Bed Where RoomCode=A.RoomCode And Flag=1) As 住宿费用
from RS_Bed A Where (EmpCode Is Not Null) And EmpCode='Em001'
paoluo 2005-04-15
  • 打赏
  • 举报
回复
--建立测试环境
Create table RS_Room
(RoomCode Varchar(10),
EMoney Int)

Create table RS_Bed
(BedCode Varchar(10),
RoomCode Varchar(10),
EmpCode Varchar(10),
Flag Bit)
GO
--插入数据
Insert RS_Room Values('001', 600)
Insert RS_Room Values('002', 500)

Insert RS_Bed Values('001-01', '001', 'Em001', 1)
Insert RS_Bed Values('001-02', '001', 'Em002', 1)
Insert RS_Bed Values('001-03', '001', 'Em003', 1)
Insert RS_Bed Values('001-04', '001', Null , 0)
Insert RS_Bed Values('002-01', '002', Null , 0)
Insert RS_Bed Values('002-02', '002', 'Em004', 1)
Insert RS_Bed Values('002-03', '002', Null , 0)
Insert RS_Bed Values('002-04', '002', Null , 0)
GO
--测试
Select
EmpCode,
(Select EMoney from RS_Room Where RoomCode=A.RoomCode)/(Select Count(*) from RS_Bed Where RoomCode=A.RoomCode And Flag=1) As 住宿费用
from RS_Bed A Where (EmpCode Is Not Null)
Order By RoomCode
--删除测试环境
Drop table RS_Room,RS_Bed
--结果
/*
RoomCode 住宿费用
Em001 200
Em002 200
Em003 200
Em004 500
*/

34,587

社区成员

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

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