SELECT StringNum
,Price1
,Price2
,(Price1 - LimitP1) AS OverP1
,(Price2 - LimitP2) AS OverP2
FROM (
SELECT a.StringNum
,Price1
,Price2
,'T1' AS T1
FROM GoodLuck10 a
LEFT JOIN (
SELECT StringNum
,SUM(Price1) AS Price1
,SUM(Price2) AS Price2
FROM GoodLuck
WHERE InputType = 'T1'
GROUP BY stringNum
) b ON a.StringNum = b.StringNum
) c
LEFT JOIN GoodLuckConfig d ON c.T1 = d.InputType
UNION ALL
SELECT StringNum
,Price1
,Price2
,(Price1 - LimitP1) AS OverP1
,(Price2 - LimitP2) AS OverP2
FROM (
SELECT a.StringNum
,Price1
,Price2
,'T1' AS T1
FROM GoodLuck10 a
LEFT JOIN (
SELECT StringNum
,SUM(Price1) AS Price1
,SUM(Price2) AS Price2
FROM GoodLuck
WHERE InputType = 'T1'
GROUP BY stringNum
) b ON a.StringNum = b.StringNum
) c
LEFT JOIN GoodLuckConfig d ON c.T1 = d.InputType