这很简单,但我在填充临时表时遇到问题,其中TypeRec中的不同值的数量不大于每个MatchId和RefNum字段的数量。
CREATE TABLE #TempTable (MatchId int, RefNum char(50), TypeRec char(50))
INSERT INTO #TempTable (MatchId, RefNum, TypeRec)
SELECT t.MatchId,
t.refNum,
t.TypeRec
FROM Transaction t (nolock)
WHERE t.UserText = 'Proposed'
AND t.CompanyId = 4
AND t.RefNum = 'CreditCard'
GROUP BY t.matchId, t.RefNum, t.TypeRec
HAVING count(distinct t.TypeRec) = 1
答案 0 :(得分:2)
只需从typerec
移除group by
并使用min()
或max()
:
INSERT INTO #TempTable (MatchId, RefNum, TypeRec)
SELECT t.MatchId, t.refNum, min(t.TypeRec)
FROM Transaction t (nolock)
WHERE t.UserText = 'Proposed'
AND t.CompanyId = 4
AND t.RefNum = 'CreditCard'
GROUP BY t.matchId, t.RefNum
HAVING count(distinct t.TypeRec) = 1;
这会计算TypeRec
和MatchId
的每个组合的RefNum
个数。只有TypeRec
时,它才返回这样的对。使用min()
只是为了获得该值 - 一个值的最小值就是该值。