Sql 使用计数左连接同一表的2
我尝试使用以下SQL组合表中的两个结果:Sql 使用计数左连接同一表的2,sql,sql-server,left-join,Sql,Sql Server,Left Join,我尝试使用以下SQL组合表中的两个结果: 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)
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
您可以发布
数据表中的一组行样本吗?我想这比你的两个子查询看起来要简单。我想我自己解决了。从数据组中选择Datepart(mm,starttime)、COUNT(当usertype='Subscriber'时为1 END)、COUNT(当usertype='Customer'时为1 END)、COUNT(当usertype='Customer'时为1 END)COUNT(当usertype='Customer'时为1 END)和COUNT(当usertype='Customer'时为1 END)COUNT(COUNT)是的,这可能是最简单的方法。你可以在下面贴出你自己的答案。