使用SQL Server 2012.我有一个名为deals的表,其中包含一个名为deal_id的主键以及其他10个字段。我还有一个名为deals_country的表,其中包含一个名为deal_id的外键。
交易记录可能包含交易国家/地区的大量记录。我想要做的是计算每笔交易中的deal_id出现在deals_country中的次数?
以下是我没有成功的尝试。
select MA_DEALS.*, MA_DEALS_COUNTRY.mycount
from MA_DEALS cross apply
(
select count(MA_DEALS_COUNTRY.deal_id) as mycount
from MA_DEALS_COUNTRY
group by MA_DEALS_COUNTRY.deal_id
) MA_DEALS_COUNTRY
order by MA_DEALS.deal_id
答案 0 :(得分:1)
试试这个:
SELECT D.*,
DC.N
FROM MA_DEALS D
LEFT JOIN ( SELECT deal_id, COUNT(*) N
FROM MA_DEALS_COUNTRY
GROUP BY deal_id) DC
ON D.deal_id = DC.deal_id
答案 1 :(得分:1)
虽然您可以使用CROSS APPLY
,但我会从基本的JOIN
和GROUP BY
查询开始:
select MA_DEALS.*, dc.mycount
from MA_DEALS d left join
(select dc.deal_id, count(dc.deal_id) as mycount
from MA_DEALS_COUNTRY dc
group by dc.deal_id
) dc
on d.deal_id = dc.deal_id
order by d.deal_id;