Answers for "small prob in join?"
https://ask.sqlservercentral.com/questions/41109/small-prob-in-join.html
The latest answers for the question "small prob in join?"Answer by Kevin Feasel
https://ask.sqlservercentral.com/answers/41115/view.html
My answer is very similar to @Kev Riley's (so much so that I didn't post it once I saw his...), but with your latest requirement, here goes:
declare @t1 table
(
resid char(1),
mid tinyint,
s int
)
declare @t2 table
(
mid tinyint,
val int
)
insert into @t1(resid, mid, s) values
('a', 2, 10),
('b', 2, 10),
('a', 2, 10),
('b', 3, 20),
('c', 3, 20);
insert into @t2(mid, val) values
(2, 10),
(3, 20);
select
sum(r.resids) as numResids,
SUM(t2.val) as summation
from
@t2 t2
inner join (select mid, COUNT(resid) as resids from @t1 group by mid) r on r.mid = t2.mid
where
t2.mid in (2, 3);
The load statements are specific to SQL 2008 and later, but the select statement (which is the important part here) will work in previous editions.Mon, 06 Jun 2011 04:57:43 GMTKevin FeaselAnswer by Kev Riley
https://ask.sqlservercentral.com/answers/41111/view.html
If the second table already has the sum(val) aggregated by mId, then you need to join differently
declare @MyFirstTable table (resid char(1), mId int, [sum] int)
insert into @MyFirstTable select 'a',2,10
insert into @MyFirstTable select 'b',2,10
insert into @MyFirstTable select 'a',2,10
insert into @MyFirstTable select 'b',3,20
insert into @MyFirstTable select 'c',3,20
declare @MySecondTable table (mId int, val int)
insert into @MySecondTable select 2,10
insert into @MySecondTable select 3,20
select
firsttable.countval,
secondtable.val
from
(
select
mId, COUNT(resid) as countval
from
@MyFirstTable
where mId in (2,3)
group by mId
) firsttable
join @MySecondTable secondtable on firsttable.mId = secondtable.mId
gives
countval val
----------- -----------
3 10
2 20
(2 row(s) affected)
----
Edit : OP has clarified the output requirements
Try this
select
(
select
COUNT(resid) as countval
from
@MyFirstTable
where mId in (2,3)
),
(
select SUM(val)
from @MySecondTable
where mId in (2,3)
)Mon, 06 Jun 2011 04:45:31 GMTKev Riley