具有多个记录的内部联接

时间:2014-07-04 10:27:46

标签: sql sql-server

我有2个表TblMemberDetails,TblMemberDetailsS​​ub正在使用以下sql查询来获取记录 QUERY 1

SELECT   (TblMemberDetails.MemFname +' '+TblMemberDetails.MemMname +' '+
          TblMemberDetails.MemLname)As Name,
          TblStateMaster.StateName,
          TblDistMaster.DistName,
          TblTaluqaMaster.TaluqaName
FROM TblMemberDetails INNER JOIN TblStateMaster 
ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId 
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId 
INNER JOIN TblMemberDetailsSub ON TblMemberDetails.MemId = TblMemberDetailsSub.MemId
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted') 
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetails.MemId,
TblMemberDetails.MemFname, TblMemberDetails.MemMname,
TblMemberDetails.MemLname, TblStateMaster.StateName,
TblDistMaster.DistName, TblTaluqaMaster.TaluqaName
order by TblMemberDetailsSub.MemId Asc

QUERY 2

SELECT TblMemberDetailsSub.MemId, ISNULL(sum(TblMemberDetailsSub.Amount),0) AS TotalAmount,
        TblMemberDetailsSub.PayRound, TblMemberDetailsSub.PlanName
FROM TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName, TblMemberDetailsSub.Amount
ORDER BY TblMemberDetailsSub.MemId Asc

我只想将两个表结果放在单个集合中(我用户联合但它不起作用) 如何合并单个结果的两个查询

1 个答案:

答案 0 :(得分:1)

如果每个memberId只有一行,则第一个查询中的分组不重要 TblStateMaster ,TblDistMaster ,TblTaluqaMaster您也未在第一次查询中选择TblMemberDetailsSub中的任何值。合并两个查询的一种方法如下:

SELECT   (TblMemberDetails.MemFname +
          ' '+
          TblMemberDetails.MemMname +
          ' '+
          TblMemberDetails.MemLname)As Name,
          TblStateMaster.StateName,
          TblDistMaster.DistName,
          TblTaluqaMaster.TaluqaName,
          T.MemId,
          T.TotalAmount,
          T.PayRound,
          T.PlanName
FROM 
TblMemberDetails 
INNER JOIN TblStateMaster ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId 
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId 
Inner join (
select TblMemberDetailsSub.MemId,
ISNULL(sum(TblMemberDetailsSub.Amount),0)As TotalAmount,
TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName 
from TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted') 
group by TblMemberDetailsSub.MemId,TblMemberDetailsSub.PayRound,TblMemberDetailsSub.PlanName,TblMemberDetailsSub.Amount
) T ON TblMemberDetails.MemId = T.MemId
order by T.MemId Asc