如何编写SQL Query,以避免重复?

时间:2015-02-18 18:02:14

标签: mysql sql-server

ID     Balance      Account Type      Date
1245    100           HR              01-01-15
1245    500           HC              02-01-15
1325    200           HC              03-01-15
1789    400           HC              04-01-15

在这种情况下,我只想要帐户类型为HC且余额不等于零的行

select * from ABC where Account Type = 'HC'
and Balance<>0; 

无效。

我只想要帐户类型为HC且余额为&gt的ID; 0并且对于该ID,它不应该具有作为HR的帐户类型。

2 个答案:

答案 0 :(得分:1)

试试这个:

select * from ABC
where Account_Type = 'HC'
and Balance<>0
and not exists(
    select 'HR'
    FROM abc a2
    where a2.account_type = 'HR'
   AND a2.id = abc.id
)

答案 1 :(得分:0)

这应该有效:

select * 
from ABC A1 
where 
  Account Type = 'HC' and 
  Balance<>0 and 
  not exists (
    select 1 
    from ABC A2 
    where 
      A1.ID = A2.ID And 
      A2.Type = 'HR'
  )