有三个表。新闻表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
这样好像查询不出来
请各位指教

解决方案 »

  1.   


    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
      

  2.   

    Branch是部门表啊。新闻表里有个部门ID。表示哪个部门发布的新闻。Items表示栏目,新闻表里有ItemId表示这条新闻属于哪个栏目的
      

  3.   

    jackyerror 
    case when N.status <> 99 and I.type = 1 then 1 else 0 end
    这句是什么意思啊?
      

  4.   

    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
      

  5.   

    当n.status不等于99并且i.type等于1是取1 否则取0
      

  6.   

    jackyerror  的写法
    我加了个条件
    B.Status<>99
    为什么B.Status=99的数据也查询出来了啊?
      

  7.   

    jackyerror     的写法 
    我加了个条件 
    B.Status <> 99 
    为什么B.Status=99的数据也查询出来了啊?=========================================你条件加在哪里啦?
      

  8.   

    加在group by 前面啊。
    我还加了其他条件。
    现在新闻表里的时间范围的可以用,
    就是部门的条件好像没用
    是不是因为left join?
      

  9.   

    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...