我在下面写了表和SQL查询,这个查询不应该返回任何结果但返回ID = 1
,SQL查询有什么问题?有人可以帮忙吗?
**注意balance
数据类型为decimal
,其余为varchar
ID code balance level
1 C 150.00
1 P 40027.42 F
1 P 40027.42 F
select distinct ID from table
(
(code = 'P' and balance = 40027.42 and level = 'F') or
(code = 'C' and balance = 151.00 )
)
group by ID
having count(ID) >=2
答案 0 :(得分:1)
如果您不想计算两次相同的code
,可以使用count(distinct code)
:
select ID
from t
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(distinct code) >=2
如果您只想计算一组不同的值,可以将派生表/子查询用于select distinct
行:
select ID
from (
select distinct id, code, balance, level
from t
) as s
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(ID) >=2
两者的rextester演示:http://rextester.com/LBKO57534