如何在连接查询中使用计数

时间:2013-05-02 15:46:14

标签: sql join count

我必须在列上的两个表之间创建连接,并显示它们连接的字段的计数

例如,此处' 业务'是我想要加入的关键。

第一个查询是

select 
    [business], count(*) as total from dimhexpand group by [business] 

我得到一个结果:

DA  54100

Dual    6909

ECM 1508

Flex    15481

另一个问题是:

select business, count (*) from LODG
group by business order by business

查询的结果是:

DA  100

Dual    909

ECM 508

Flex    15481

我希望通过连接这两个表来返回数据,以显示类似

的内容
**dimhexpand.business dimhexpand.count LODG.Count**
DA          54100       100 

Dual            6909        909

ECM         1508        508

Flex            15481       151481

2 个答案:

答案 0 :(得分:0)

您可以加入business列上的两个表:

select d.business, 
  count(d.business) as dimCount,
  l.lodgCount
from dimhexpand d
left join
(
  select business, count (*) lodgCount
  from LODG 
  group by business 
) l
  on d.business = l.business
group by d.business;

如果每个表中可能有不同的business值,那么您可以在两个查询之间使用FULL OUTER JOIN,类似于:

select coalesce(d.business, l.business),
  coalesce(d.dimCount, 0) dimCount,
  coalesce(l.lodgCount, 0) lodgCount
from
(
  select business, count(*) as dimCount 
  from dimhexpand 
  group by business
) d
full outer join
(
  select business, count (*) lodgCount
  from LODG 
  group by business 
) l
  on d.business = l.business

答案 1 :(得分:0)

有些问题需要回答以提供准确的答案。你可以在dimhexpand开展业务而不是LODG,反之亦然吗? 如果您总是在业务上一对一,那么上面提供的子查询答案将有效。如果没有,如果没有完全加入,你将从任何一个表中丢失值。 如果你可以让任何一个表都有唯一的业务,你可以使用内存表吗?

Declare @tblDimhExpand TABLE (
    business varchar(50) null, 
    CountDimHExpand int null
    )
Declare @tblLoDG TABLE (
    business varchar(50) null, 
    CountLodG int null
    )

Insert into @tblDimhExpand select business, count(*) from DimhExpand Group By Business

Insert into @tblLoDG select business, count(*) from LODG Group By Business

Select coalesce(dim.business, lodg.business) as Business, dim.countDimhExpand, lodg.countlodg
    From @tblDimhExpand dim
    FULL JOIN @tblLodG lodg on dim.Business = lodg.Business

这将返回来自两个表的所有业务记录,无论它们是否存在于另一个表中,并且当两者都存在时将结合结果,并且当表中仅存在一个值时,为该表提供NULL。