簡體   English   中英

左連接同一表的2個,計數

[英]Left joining 2 of the same table with count

我正在嘗試使用以下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

希望這行得通:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM