Dada a seguinte tabela:
CREATE TABLE `tb_plano_saude` (
`id` int(11) NOT NULL,
`Titular` varchar(10) DEFAULT NULL,
`matricula` varchar(10) DEFAULT NULL,
`CPF` varchar(15) DEFAULT NULL,
`Nome` varchar(45) DEFAULT NULL,
`boleano` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
com os seguintes dados:
1 TOP 101060 97424613170 MARIA FLAVIO 1
2 DTOP 101060 63455847625 JOAO FLAVIO 0
3 DTOP 101060 94443050744 BETO FLAVIO 0
4 DTOP 202061 87424613170 MARIA GUSTAVO 0
5 DTOP 202061 43455847625 MARCELO GUSTAVO 0
6 TOP 202061 34443050744 PAULO GUSTAVO 1
a query que fiz abaixo APARENTEMENTE retorna o resultado que eu entendi que você queria
IMPORTANTE.. assumi que o campo "boleano" também é um indicador de titularidade
select * from (
SELECT matricula, cpf,titular,nome, boleano, (matricula + boleano) as b
FROM tb_plano_saude
GROUP BY matricula, cpf
order by matricula, titular desc, cpf) tb
order by b desc
RESULTADO:
202061 34443050744 TOP PAULO GUSTAVO 1 202062
202061 43455847625 DTOP MARCELO GUSTAVO 0 202061
202061 87424613170 DTOP MARIA GUSTAVO 0 202061
101060 97424613170 TOP MARIA FLAVIO 1 101061
101060 63455847625 DTOP JOAO FLAVIO 0 101060
101060 94443050744 DTOP BETO FLAVIO 0 101060
CASO o campo "boleano" não seja indicador de titularidade pode-se concatenar a matricula e o primeiro caracter do campo "titular" para ter o mesmo efeito conforme abaixo
select * from (
SELECT matricula, cpf,titular,nome, boleano, CONCAT(matricula ,
SUBSTR(titular,1,1)) as b
FROM tb_plano_saude
GROUP BY matricula, cpf
order by matricula, titular desc, cpf) tb
order by b desc
Obtendo o resultado
202061 34443050744 TOP PAULO GUSTAVO 1 202061T
202061 43455847625 DTOP MARCELO GUSTAVO 0 202061D
202061 87424613170 DTOP MARIA GUSTAVO 0 202061D
101060 97424613170 TOP MARIA FLAVIO 1 101060T
101060 63455847625 DTOP JOAO FLAVIO 0 101060D
101060 94443050744 DTOP BETO FLAVIO 0 101060D
GROUP_BY
? – Leonardo Alves Machado 27/03 às 12:09