表1 :
Id | Mapping_Id (INT)
--- ---------------
1 1001
2 1002
3 1003
4 1004
表2 :
Name | ResultId (nvarchar(Max))
---- -------------------------
AB 1001,1002,1003,1004
现在,我需要通过在列 Mapping_Id 和 ResultId上使用 Table1 和 Table2 来从表1中提供Id总和的查询
即:选择总和(A.Id),B.Name来自表1 A,表2 B,其中A.Mapping_Id(B.ResultId)
预期结果:
Count | ResultId (nvarchar(Max))
----- -------------------------
10 AB
答案 0 :(得分:2)
尝试此查询:
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
答案 1 :(得分:1)
试试这个......
Select sum(A.Id),B.Name from Table1 A,Table2 B where A.Mapping_Id in (select value from SplitDelimited(B.ResultId,','))
使用SplitDelimited功能..
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