组通过阻止Having子句给出期望的结果

时间:2014-03-25 13:24:18

标签: sql sql-server

这很简单,但我在填充临时表时遇到问题,其中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  

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;

这会计算TypeRecMatchId的每个组合的RefNum个数。只有TypeRec时,它才返回这样的对。使用min()只是为了获得该值 - 一个值的最小值就是该值。