SQL查询以获取仅具有特定类型的记录

时间:2019-02-14 09:42:45

标签: sql sql-server tsql

我有以下记录类型

account     amount  code        type        c_date
AAAA        100.00  111         C           2018-01-01
AAAA        200.00  666         C           2018-01-01
AAAA        300.00  777         C           2018-01-01 
BBBB        500.00  111         C           2018-01-01 
BBBB        400.00  222         B           2018-01-01 
BBBB        600.00  111         C           2018-01-01 
DDDD        100.00  111         C           2018-01-01 
DDDD        200.00  777         C           2018-01-01 
EEEE        900.00  333         B           2018-01-01 
EEEE        1000.00 222         B           2018-01-01 
EEEE        1200.00 111         C           2018-01-01
FFFF        123.00  111         C           2018-01-01 
GGGG        1223.00 222         B           2018-01-01 

我只需要检索仅在type = 'C'上拥有的帐户 所需记录为:

AAAA 
DDDD
FFFF

我的查询:

SELECT DISTINCT ACCOUNT,TYPE,COUNT(*) FROM Table_1
WHERE ACCOUNT IN (SELECT account
  FROM Table_1
  group by account
)  
GROUP BY ACCOUNT,TYPE
HAVING TYPE = 'C' 
ORDER BY 1

2 个答案:

答案 0 :(得分:3)

您可以使用NOT EXISTS

SELECT * -- or DISTINCT Account
FROM t
WHERE NOT EXISTS (
    SELECT 1
    FROM t AS x
    WHERE account = t.account
    AND type <> 'C'
)

答案 1 :(得分:1)

您可以尝试

SELECT Distinct account
FROM Table_1
Where type = 'C'
AND Account NOT IN (Select Account from Table_1 Where type <> 'C')

您可以查看现场演示Here