有一表与表关联问题求教

Delphi_jpy 2009-12-16 09:54:00
主表(Opt_Receive_Send ):
id customerid opt_date gcid(从表gcid字段) work_id
1 1 2009-12-16 123 1
2 2 2009-12-16 null (代表未建档,从表中无记录) 7

从表(Archives):
id gcid bar_code
1 123 333
2 222 666

要求对主表汇总,work_id=7代表气瓶发送,work_id=1 代表气瓶回收,统计今天的气瓶发送回收情况:
select customerid ,sum(case when work_id='7' then 1 else 0 end) as 今日发送 ,
sum(case when work_id='1' then 1 else 0 end) as 今日回收 from Opt_Receive_Send
形成以下结果:
customerid opt_date 今日发送 今日回收
1 2009-12-16 1 1
当我关联到从表之后还能形成一下这样的查询结果
customerid opt_date 今日发送 今日回收
1 2009-12-16 1 1
...全文
54 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2009-12-16
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 delphi_jpy 的回复:]
引用 5 楼 dawugui 的回复:
SQL codeselect m.customerid,
      m.opt_date,sum(case m.work_idwhen7then1else0end)[今日发送],sum(case m.work_idwhen1then1else0end)[今日回收]from Opt_Receive_Send m , Archives nwhere m.gcid= n.gcidgroupby m.?-

这个有点问题的,当从表没有对应记录的时候结果是有问题的
[/Quote]

select m.customerid,
m.opt_date,
sum(case m.work_id when 7 then 1 else 0 end) [今日发送],
sum(case m.work_id when 1 then 1 else 0 end) [今日回收]
from Opt_Receive_Send m left join Archives n
on m.gcid = n.gcid
group by m.customerid, m.opt_date
Delphi_jpy 2009-12-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 dawugui 的回复:]
SQL codeselect m.customerid,
m.opt_date,sum(case m.work_idwhen7then1else0end)[今日发送],sum(case m.work_idwhen1then1else0end)[今日回收]from Opt_Receive_Send m , Archives nwhere m.gcid= n.gcidgroupby m.?-
[/Quote]
这个有点问题的,当从表没有对应记录的时候结果是有问题的
dawugui 2009-12-16
  • 打赏
  • 举报
回复
select m.customerid,
m.opt_date,
sum(case m.work_id when 7 then 1 else 0 end) [今日发送],
sum(case m.work_id when 1 then 1 else 0 end) [今日回收]
from Opt_Receive_Send m , Archives n
where m.gcid = n.gcid
group by m.customerid, m.opt_date
Delphi_jpy 2009-12-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 zoezs 的回复:]
SQL codeselect T.*,a.gcidfrom
(select customerid ,sum(casewhen work_id='7'then1else0end)as 今日发送 ,sum(casewhen work_id='1'then1else0end)as 今日回收from Opt_Receive_Sendgroupby customerid) Tleftjoin Archiv?-
[/Quote]
主从表是通过gcid关联的
Zoezs 2009-12-16
  • 打赏
  • 举报
回复

select T.*,a.gcid from
(select customerid ,sum(case when work_id='7' then 1 else 0 end) as 今日发送 ,
sum(case when work_id='1' then 1 else 0 end) as 今日回收 from Opt_Receive_Send
group by customerid) T left join Archives a on a.customerid =T.customerid
Delphi_jpy 2009-12-16
  • 打赏
  • 举报
回复
跪求
bancxc 2009-12-16
  • 打赏
  • 举报
回复
9.76
..

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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