SQL Group By COUNT in two

时间:2015-06-18 22:30:21

标签: sql sql-server

在某个表格中,我正在尝试获取包含CCID行的TypeID,而不包含任何其他TypeID行。以下SQL查询似乎不正确

SELECT
  T1.CCID,
  T1.TrCnt AS OurTypeCnt,
  T2.TrCnt AS NotOurTypeCnt
FROM (SELECT
       CCID,
       COUNT(CCID) AS TrCnt
     FROM CCsTransactions
     WHERE TypeID = 5
     GROUP BY CCID) T1,
     (SELECT
       CCID,
       COUNT(CCID) AS TrCnt
     FROM CCsTransactions
     WHERE TypeID <> 5
     GROUP BY CCID) T2
WHERE ((T1.TrCnt >= 1)
AND (T2.TrCnt < 1))

它返回空,因为结果看起来很有趣(TrCnts中没有0值)。

有更好的方法吗?

3 个答案:

答案 0 :(得分:2)

使用不同的WHERE条件访问同一个表两次。这可以用CASE代替:

SELECT CCID, 
   COUNT(CASE WHEN TypeID = 5 THEN CCID END) as OurTypeCnt,
   COUNT(CASE WHEN TypeID <> 5 THEN CCID END) as NotOurTypeCnt
FROM CCsTransactions 
GROUP BY CCID
HAVING ((OurTypeCnt >= 1) AND (NotOurTypeCnt < 1))

答案 1 :(得分:1)

您完成查询可以写成:

select ccid
from CCsTransactions
group by ccid
having sum(case when TypeId = 5 then 1 else 0 end) > 0 and
       sum(case when TypeId <> 5 then 1 else 0 end) = 0;

或者,更简单的方法是:

select ccid
from CCsTransactions
group by ccid
having max(TypeId) = 5 and min(TypeId) = 5;

答案 2 :(得分:0)

以下是您可以实现结果的另一种方式:

WITH HasTheType
AS (SELECT
  CCID
FROM CCsTransactions
WHERE TypeID = 5
GROUP BY CCID
HAVING COUNT(*) > 0),
OtherTypes
AS (SELECT
  CCID
FROM CCsTransactions
WHERE TypeID <> 5
GROUP BY CCID
HAVING COUNT(*) > 0)

SELECT
  T.CCID
FROM HasTheType T
LEFT JOIN OtherTypes O
  ON T.CCID = O.CCID
WHERE O.CCID IS NULL