如何检查某个值是否存在或是否存在两次?

时间:2017-11-09 09:14:44

标签: mysql sql database

所以我有一张看起来像这样的表:

ID  CUR_Valid
1   N 
1   N
1   N
1   N
1   N
1   Y
2   N
2   N
2   Y
3   Y

因此,您可以看到一个ID只能被允许有一个y。我想写一个声明,告诉我没有Y或者更多Y的ID。

到目前为止我的代码看起来像这样:

Select [BILL_ID]
      ,[Bill_MONTH]
      ,[CUR_VALID]
      ,COUNT(CUR_VALID)
FROM DB.dbo.table
WHERE CUR_VALID = 'Y'
GROUP BY [BILL_ID]
      ,[Bill_MONTH]
      ,[CUR_VALID]
 Having COUNT(CUR_VALID) > 1 OR COUNT(CUR_VALID) <1

我不确定什么是错的。有人能指出我正确的方向吗?

4 个答案:

答案 0 :(得分:1)

试试这个答案。希望这可以帮到你:

Select [BILL_ID]
      ,[Bill_MONTH]
      ,[CUR_VALID]
      ,COUNT(CUR_VALID)
FROM DB.dbo.table
--WHERE CUR_VALID = 'Y'
GROUP BY [BILL_ID]
      ,[Bill_MONTH]
      ,[CUR_VALID]
 Having COUNT(CASE WHEN CUR_VALID = 'Y' THEN 1 END) > 1 OR COUNT(CASE WHEN CUR_VALID = 'Y' THEN 1 END) <1

当您设置WHERE CUR_VALID = 'Y'条件时,它会删除没有Y的记录。

尝试此更新,ID数量。

Select COUNT(1)[No of Ids]
FROM DB.dbo.table
GROUP BY [BILL_ID]
      ,[Bill_MONTH]
      ,[CUR_VALID]
 Having COUNT(CASE WHEN CUR_VALID = 'Y' THEN 1 END) > 1 OR COUNT(CASE WHEN CUR_VALID = 'Y' THEN 1 END) <1

返回Ids数。

答案 1 :(得分:1)

使用

SQL Aliases

算作totalValid

Select [BILL_ID]
          ,[Bill_MONTH]
          ,[CUR_VALID]
          ,COUNT(CUR_VALID) as totalValid
    FROM DB.dbo.table
    WHERE CUR_VALID = 'Y'
    GROUP BY [BILL_ID]
          ,[Bill_MONTH]
          ,[CUR_VALID]
     Having  totalValid > 1 OR  totalValid <1

答案 2 :(得分:1)

这是一个示例查询,用于演示如何识别没有Y的人或者有两个或更多Y的人

with dat
as
(
select 1 id,'N' cur_valid  union all 
select 1,'N' union all
select 1,'N' union all
select 1,'N' union all
select 1,'N' union all
select 1,'Y' union all
select 2,'N' union all
select 2,'N' union all
select 2,'Y' union all
select 3,'Y' union all
select 4,'Y' union all /* two Ys */
select 4,'Y' union all
select 5,'N' /* no Y */)
select id
from
(
   select id,sum(case when cur_valid='Y' then 1 else 0 end) x
   from dat
   group by id
) ilv
where x<>1

这可以浓缩为

with dat
as
(
select 1 id,'N' cur_valid  union all 
select 1,'N' union all
select 1,'N' union all
select 1,'N' union all
select 1,'N' union all
select 1,'Y' union all
select 2,'N' union all
select 2,'N' union all
select 2,'Y' union all
select 3,'Y' union all
select 4,'Y' union all /* two Ys */
select 4,'Y' union all
select 5,'N' /* no Y */)
select id
from dat
group by id
having sum(case when cur_valid='Y' then 1 else 0 end)<>1

答案 3 :(得分:1)

可以像这样使用自联接

select d1.id, count(d2.id)
from (select id from dat group by id) d1
left join dat d2 on d1.id = d2.id and d2.cur_valid = 'Y'
group by d1.id
having count(d2.id) <> 1

demo - 感谢@Abbennett获取数据