构造SQL语句以检索相同/不同表中特定记录的count()

时间:2012-09-14 10:01:36

标签: sql sql-server sql-server-2008

之前我曾询问过有关此问题的问题,但必须承认对基于SQL的解决方案存在偏见,现在我找不到问题,所以我会再试一次,仔细说出来并对所提供的任何解决方案更加开放

我有两张桌子:

tblCurrent 
 Ref  | CustomerID | ... .. .. .  . |
X001
X002
X003


tblHistorical 
 Ref   | ... .. .. .  . |  Missing | Matched
X001   | ... .. .. .  . |  TRUE    | FALSE
X001   | ... .. .. .  . |  FALSE   | FALSE
X002   | ... .. .. .  . |  TRUE    | TRUE
X002   | ... .. .. .  . |  TRUE    | FALSE
X003   | ... .. .. .  . |  FALSE   | FALSE
X003   | ... .. .. .  . |  TRUE    | TRUE

Ref在tblCurrent中是唯一的,但在历史中不是。

如何构建一个基于tblCurrent的视图,该视图导致另外三列计算tblHistorical中的记录数:

  • 匹配Ref AND Missing为TRUE

  • 匹配Ref AND Missing为False

  • 匹配Ref AND Matched为True

请注意,我需要根据类似的标准添加额外的列来计算tblHistorical中的记录数。

4 个答案:

答案 0 :(得分:3)

SELECT R.Ref,
SUM(CASE WHEN H.Missing = TRUE THEN 1 ELSE 0 END) as MissingTrue,
SUM(CASE WHEN H.Missing = FALSE THEN 1 ELSE 0 END) as MissingFalse,
SUM(CASE WHEN H.Matched = TRUE THEN 1 ELSE 0 END) as MatchedTrue
FROM tblRef R JOIN tblHistorical H
ON R.Ref = H.Ref

答案 1 :(得分:1)

我认为你需要对LEFT JOIN使用ref因为tblHistorical表可能不存在SELECT a.ref, SUM(CASE WHEN b.Missing = 'True' THEN 1 ELSE 0 END) missingTrue, SUM(CASE WHEN b.Missing = 'False' THEN 1 ELSE 0 END) missingFalse, SUM(CASE WHEN b.Matched = 'True' THEN 1 ELSE 0 END) matchTrue FROM tblCurrent a LEFT JOIN tblHistorical b on a.ref = b.ref GROUP BY a.ref

{{1}}

答案 2 :(得分:1)

SELECT R.Ref,
SUM(CASE WHEN H.Missing = TRUE THEN 1 ELSE 0 END) as MissingTrue,
SUM(CASE WHEN H.Missing = FALSE THEN 1 ELSE 0 END) as MissingFalse,
SUM(CASE WHEN H.Matched = TRUE THEN 1 ELSE 0 END) as MatchedTrue
FROM tblRef R 
INNER JOIN tblHistorical H
ON R.Ref = H.Ref
Group by R.Ref

答案 3 :(得分:1)

SELECT T.REF,
        COUNT(CASE WHEN H.MISSING = 'TRUE' THEN 1  END) AS MISSINGTRUE,
        COUNT(CASE WHEN H.MISSING = 'FALSE' THEN 1 END) AS MISSINGFALSE,
        COUNT(CASE WHEN H.MATCHED = 'TRUE' THEN 1  END) AS MATCHEDTRUE
FROM   TBLREF T 
JOIN   TBLHISTORICAL H
ON     R.REF = H.REF
GROUP BY T.REF