Mysql 查询布尔和if语句
所以我有一个表名报告这样的细节Mysql 查询布尔和if语句,mysql,sql,Mysql,Sql,所以我有一个表名报告这样的细节 No(autoincrement) Code Stats(bool) -------------------------------------- 1 F01 0 2 F02 0 3 F03 0 4 F03
No(autoincrement) Code Stats(bool)
--------------------------------------
1 F01 0
2 F02 0
3 F03 0
4 F03 1
5 F03 1
6 F04 1
7 F04 0
因此,场景是,如果代码的stats值为true,则显示所有值,如果代码的stats值为true,则仅显示false,因此我想要的结果是(注意:一个代码的值false总是有一条记录)
因为f01和f02没有值stats true,所以显示它们,对于案例f03和f04,因为have value true for stat显示它们都为true,忽略false值
那么我的查询是如何得到结果的呢看起来你需要
densite\u RANK()
函数
select * from
(
select *,
dense_rank() over (partition by Code order by Stats desc) Seq
from table t
) t
where Seq = 1
如果不想使用子查询
表单,可以通过SQL Server中提供的TOP with ties来探索上述内容
select top 1 with ties [No(autoincrement)], Code, [Stats(bool)]
from table t
order by dense_rank() over (partition by Code order by [Stats(bool)] desc)
因为MySQL
没有分析功能。因此,您可以通过UNION ALL
select *
from table t
where exists (
select 1 from table
where autoincrement = t.autoincrement and Stats = 1
) UNION ALL
select *
from table t
where not exists (
select 1 from table
where code = t.code and Stats = 1)
ORDER BY 1
输出
No Code Stats
1 F01 0
2 F02 0
4 F03 1
5 F03 1
6 F04 1
演示
您正在使用哪个dbms?我使用mysql作为我的dbms检查我的解决方案使用mysql DenseRank@inheavenah如果我使用mysql作为查询,如何使用densite_rank选择1中的1是?@InheavenA<代码>选择1意味着为满足筛选条件的每个匹配记录返回1。
SELECT No,Code,Stats FROM
(SELECT No,Code,Stats,
Case when @Code = t.Code Then
Case when @stats != t.stats Then
@DenseRank := @DenseRank + 1
ELSE
@DenseRank := 1
END
Else
@DenseRank := 1
END as DenseRank,
@Code :=t.code as VarCode,
@stats :=t.stats as varstatus
FROM Table1 t join
(Select @DenseRank := 1,@Code := '',@stats := '' )r
Order BY CODE,Stats DESC)
AS T1
WHERE
DenseRank=1
Order BY CODE,Stats DESC;
No Code Stats
1 F01 0
2 F02 0
4 F03 1
5 F03 1
6 F04 1