如何根据列中值的计数比较来提取记录

时间:2014-06-09 19:34:06

标签: sql sql-server count where

请原谅标题,但我不知道该写些什么。所以这就是我所拥有的 -

CUSTOMERKEY, IDENT, DEBIT_CREDIT

1,1000,'D'
2,1000,'C'
3,1001,'D'
4,1000,'D'
5,1000,'D'
.
.
.

我想写一个SQL Server查询来提取相同的IDENT,其中'D'的计数大于'C'的计数

1 个答案:

答案 0 :(得分:7)

首先:

SELECT IDENT
FROM CUSTOMER
GROUP BY IDENT
HAVING  SUM(CASE WHEN DEBIT_CREDIT = 'D' THEN 1 ELSE 0 END) >
        SUM(CASE WHEN DEBIT_CREDIT = 'C' THEN 1 ELSE 0 END)

第二

SELECT IDENT
FROM CUSTOMER
GROUP BY IDENT
HAVING  SUM(CASE WHEN DEBIT_CREDIT = 'D' THEN 1 ELSE 0 END) =
        SUM(CASE WHEN DEBIT_CREDIT = 'C' THEN 1 ELSE 0 END)