Ray
Ray

Reputation: 188

Sql Query with "IN" clause across two tables and columns

Table1:

 Id | Mapping_Id (INT)
 --- ---------------
  1    1001
  2    1002
  3    1003
  4    1004

Table2:

 Name | ResultId (nvarchar(Max))
 ----  -------------------------
  AB    1001,1002,1003,1004

Now, i need query which give sum of Id from Table1, by using Table1 and Table2 on columns Mapping_Id and ResultId

i.e: something like Select sum(A.Id),B.Name from Table1 A,Table2 B where A.Mapping_Id in (B.ResultId)

expected result:

 Count | ResultId (nvarchar(Max))
 -----  -------------------------
  10       AB

Upvotes: 1

Views: 713

Answers (2)

Darshak
Darshak

Reputation: 867

Try this...

Select sum(A.Id),B.Name from Table1 A,Table2 B where A.Mapping_Id in (select value from SplitDelimited(B.ResultId,','))

Use SplitDelimited fuction for that..

ALTER FUNCTION [dbo].[SplitDelimited]
(   
    @List nvarchar(MAX),
    @SplitOn nvarchar(1)
)
RETURNS @RtnValue table (
    Id int identity(1,1),
    Value nvarchar(MAX)
)

AS
BEGIN
    While (Charindex(@SplitOn,@List)>0)
    Begin 
        if(len(@List) > 0)
        begin
            Insert Into @RtnValue (value)
            Select 
                Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) 
            Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
        end
    End 

    Insert Into @RtnValue (Value)
    Select Value = ltrim(rtrim(@List))

    Return
END

Upvotes: 1

Dmitry Cat
Dmitry Cat

Reputation: 475

Try this Query:

SELECT SUM(Table1.id), Table2.Name
from Table1
join Table2 on CHARINDEX(cast(Table1.Mapping_id as varchar), Table2.ResultID)>0
group by Table2.Name

Upvotes: 2

Related Questions