需要根据多组帐户作为条件运行查询。试图避免光标/ while循环场景。 @MasterGroup变量是游标迭代器,直接从Group表派生,Group表是来自Group表的一对多,然后在WHERE子句的子查询中使用。最终结果将使用@MasterGroup整数填充到新表中。有什么方法可以避免在这里使用游标/循环?非常感谢......
Insert Into SAGTranTmp
SELECT
@MasterGroup,
C1.Cust_Type,
T1.Exclude,
T1.Acct_No,
SUM(Tran_Amt) AS [Amount]
FROM dbo.Trans AS [T1]
JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
WHERE C1.Acct_No IN (
SELECT AcctNo
FROM SignAcc_Group
WHERE MasterGroup = @MasterGroup)
答案 0 :(得分:1)
假设#MasterGroup AS TABLE(MasterGroup int)。 你可以试试这个:
;WITH
temp AS (SELECT DISTINCT
mg.MasterGroup,
T1.Acct_No
FROM dbo.Trans AS [T1]
Inner JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
inner join SignAcc_Group as sg ON C1.Acct_No = sg.AcctNo
inner join #MasterGroup mg ON sg.MasterGroup = mg.MasterGroup
)
Insert Into SAGTranTmp
SELECT
t.MasterGroup,
C1.Cust_Type,
T1.Exclude,
T1.Acct_No,
SUM(Tran_Amt) AS [Amount]
FROM temp t
INNER JOIN dbo.Trans AS [T1] ON T1.Acct_No = t.Acct_No
INNER JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
GROUP BY t.MasterGroup,
C1.Cust_Type,
T1.Exclude,
T1.Acct_No
答案 1 :(得分:0)
如果我愿意,我可能会过度简化并道歉,但请尝试这一点并希望它有所帮助。
for..loop