多表查询(外查询)

nosuchtracter 2008-01-02 03:15:46
有三个表。新闻表News N,栏目表 Items I,部门表Branch B。
关系:新闻表中有BranchId,ItemId分别对应Branch和Item表,news表里status字段不等于99表示发布数,等于1表示审核的。
要求:把所有的部门查询出来,并统计每个部门发布的新闻数(status<>99),和审核的新闻数(status=1)。且Items的Type=1
我现在只做到把所有有发布新闻数的部门查询出来,没有发布新闻的部门不知道如何查询
用B left outer join N on B.Id=N.BranchId inner join I on C.ItemId=I.Id
这样好像查询不出来
请各位指教
...全文
146 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackyerror 2008-01-02
  • 打赏
  • 举报
回复
you'd better take a look on basic knowledge of SQL.

yuck, there is something wrong with my computer, i can't type Chinese character...
nosuchtracter 2008-01-02
  • 打赏
  • 举报
回复
加在group by 前面啊。
我还加了其他条件。
现在新闻表里的时间范围的可以用,
就是部门的条件好像没用
是不是因为left join?
jackyerror 2008-01-02
  • 打赏
  • 举报
回复
jackyerror 的写法
我加了个条件
B.Status <> 99
为什么B.Status=99的数据也查询出来了啊?

=========================================

你条件加在哪里啦?
nosuchtracter 2008-01-02
  • 打赏
  • 举报
回复
jackyerror 的写法
我加了个条件
B.Status<>99
为什么B.Status=99的数据也查询出来了啊?
dawugui 2008-01-02
  • 打赏
  • 举报
回复
你最好把各个表需要用到的字段和对应关系给出.
不然我们猜测出来的东西给你也没用.
free1879 2008-01-02
  • 打赏
  • 举报
回复
当n.status不等于99并且i.type等于1是取1 否则取0
yl259443 2008-01-02
  • 打赏
  • 举报
回复
select Branch,sum(fb)as fb,sum(sh)as sh
from (
select b.Branch,count(*) as fb,0
from News N
left join Branch B on B.Id=N.BranchId
left join Items I on N.ItemId=I.Id
where status <> 99 and i.Type=1
group by b.Branch
union all
select b.Branch,0,count(*) as sh
from News N
left join Branch B on B.Id=N.BranchId
left join Items I on N.ItemId=I.Id
where status = 99 and i.Type=1
group by b.Branch)a
group by Branch
nosuchtracter 2008-01-02
  • 打赏
  • 举报
回复
jackyerror
case when N.status <> 99 and I.type = 1 then 1 else 0 end
这句是什么意思啊?
nosuchtracter 2008-01-02
  • 打赏
  • 举报
回复
Branch是部门表啊。新闻表里有个部门ID。表示哪个部门发布的新闻。Items表示栏目,新闻表里有ItemId表示这条新闻属于哪个栏目的
jackyerror 2008-01-02
  • 打赏
  • 举报
回复

select
B.BranchId,
sum(case when N.status <> 99 and I.type = 1 then 1 else 0 end) pub_cnt,
sum(case when N.status = 1 and I.type = 1 then 1 else 0 end) confirmed_cnt
from
Branch B
left join News N
on B.BranchId = B.BranchId
left join Items I
on N.itemId = I.itemId
group by B.BranchId
dawugui 2008-01-02
  • 打赏
  • 举报
回复
Branch和Item表
有什么用?

34,837

社区成员

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

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