左边用计数连接同一个表中的2个

时间:2014-03-04 02:37:28

标签: sql sql-server left-join

我正在尝试使用以下SQL组合表中的2个结果:

select * (
  SELECT Datepart(mm,starttime) as Month, COUNT(*) TotalCountSub
  from data 
  where usertype='subscriber'
  group by Datepart(mm,starttime)
  having count(*) > 1
 ) a
 LEFT JOIN (
   SELECT Datepart(mm,starttime) as Month, COUNT(*) TotalCountCust
   from data
   where usertype='Customer'
   group by Datepart(mm,starttime)
   having count(*) > 1
 ) b on a.Month = b.Month
order by Datepart(mm,starttime) ASC

我想在这里实现的是将两个结果合并到一个表中:

表1

Month|TotalCountSub
1    |50
2    |123
3    |14
4    |91

表2

Month|TotalCountCust
1    |80
2    |465
3    |79
4    |84

结果应该是:

Month|TotalCountSub|TotalCountCust
1    |50           |80
2    |123          |465
3    |14           |79
4    |91           |84

1 个答案:

答案 0 :(得分:0)

希望这有效:

select a.Month, a.TotalCountSub, b.TotalCountCust from (
  SELECT Datepart(mm,starttime) as Month, COUNT(*) TotalCountSub
  from data 
  where usertype='subscriber'
  group by Datepart(mm,starttime)
  having count(*) > 1
 ) a
 INNER JOIN (
   SELECT Datepart(mm,starttime) as Month, COUNT(*) TotalCountCust
   from data
   where usertype='Customer'
   group by Datepart(mm,starttime)
   having count(*) > 1
 ) b 
ON a.Month = b.Month
order by a.Month ASC