所以我有表名报告详细信息
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然后显示它们全部,如果代码没有值true则只显示false所以我想要的结果是(注意:一个代码总是有1个值为false的记录)
No(autoincrement) Code Stats
--------------------------------------------
1 F01 0
2 F02 0
4 F03 1
5 F03 1
6 F04 1
因为f01和f02没有值stats为true然后显示它们以及对于案例f03和f04因为stat值为true显示它们全部为true并忽略false值
那么我的查询如何得到结果
答案 0 :(得分:1)
您似乎想要DENSE_RANK()
功能
select * from
(
select *,
dense_rank() over (partition by Code order by Stats desc) Seq
from table t
) t
where Seq = 1
如果您不想使用subquery
表单,可以通过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
答案 1 :(得分:0)
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
演示