Campos no Select mais não no Group By

O teu SQL deverá estar neste momento:

    select   
          ROW_NUMBER() over(order by year(ede.data)) as 'CLASSIFICAÇÃO',  
          eee.nome                        as 'NOME',   
          sum(ede.valortot)              as 'TOTAL A PAGAR',  
            case  
                when mtcpl.codcur = 1 then 'DIREITO'  
                when mtcpl.codcur = 3 then 'MEDICINA'  
                when mtcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'  
                when mtcpl.codcur = 6 then 'NUTRIÇÃO'  
                when mtcpl.codcur = 7 then 'ADMINISTRAÇÃO'  
                when mtcpl.codcur = 8 then 'EDUCÃÇÃO FÍSICA'                         
            end as 'CURSO',  
           max(turma.codtur)                    as 'TURMA', 
          isnull(ealunos.telaluno,'-')         as 'TELEFONE'  
    from eee,  
         mtcpl,  
         turma, 
         ede,  
        fl  
    where  
         mtcpl.status    = 'MA'  
    and fl.valorbaixado   = 0.0000  
    and fl.datapag is null  
    and fl.databaixa is null     
    and ede.valorpago  = 0  
    and ede.valortot > 0.00  
    and ede.datapag is null    
    and mtcpl.mataluno  = eee.matricula  
    and mtcpl.mataluno  = ede.mataluno  
    and mtcpl.perletivo = ede.perletivo  
    and mtcpl.codcur    = ede.codcur  
    and mtcpl.perletivo = turma.codperlet  
    and mtcpl.codcur    = turma.codcur  
    and ede.codlanc    = fl.idlan  
    and fl.statuslan not in (0)   
    group by eee.nome,  
             YEAR(ede.data),  
             eee.telaluno,  
             mtcpl.codcur  

Ai pmlm, o max(turma.codtur) a principio deu certo, mais tem um outro probleminha, quando descomento tudo relacionado a tabela turma
(relacionamento e ect…) a soma do “TOTAL A PAGAR” fica errada…

select ROW_NUMBER() over(order by year(ede.data)) as 'CLASSIFICAÇÃO', eee.nome as 'NOME', sum(ede.valortot) as 'TOTAL A PAGAR', case when matcpl.codcur = 1 then 'DIREITO' when matcpl.codcur = 3 then 'MEDICINA' when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO' when matcpl.codcur = 6 then 'NUTRIÇÃO' when matcpl.codcur = 7 then 'ADMINISTRAÇÃO' when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA' end as 'CURSO', max(turma.codtur) as 'TURMA', // LINHA DESCOMENTADA isnull(eee.telaluno,'-') as 'TELEFONE' from eee, matcpl, fl, turma,// LINHA DESCOMENTADA ede where matcpl.status IN ('MA') and fl.valorbaixado = 0.0000 and fl.datapag is null and fl.databaixa is null and ede.valorpago = 0 and ede.valortot > 0.00 and ede.datapag is null and matcpl.mataluno = eee.matricula and matcpl.mataluno = ede.mataluno and matcpl.perletivo = ede.perletivo and matcpl.codcur = ede.codcur and matcpl.mataluno = turma.mataluno// LINHA DESCOMENTADA and matcpl.perletivo = turma.perletivo // LINHA DESCOMENTADA and matcpl.codcur = turma.codcur// LINHA DESCOMENTADA and matcpl.grade = turma.grade // LINHA DESCOMENTADA and turma.mataluno = ede.mataluno// LINHA DESCOMENTADA and turma.perletivo = ede.perletivo// LINHA DESCOMENTADA and turma.codcur = ede.codcur// LINHA DESCOMENTADA and turma.mataluno = eee.matricula// LINHA DESCOMENTADA and ede.mataluno = eee.matricula and ede.codlanc = fl.idlan and fl.statuslan not in (0) group by eee.nome, year(ede.data), eee.telaluno, mtcpl.codcur

A Princípio julgo-me que o problema está ao relacionar a tabela turma com as outras tabelas, mais para aparecer a turma tenho que utiliza-la…

Se tires o max e colocares o turma no group by como aparece? E se depois colocares o max e retirares do group by? Podes mostrar casos concretos onde esteja errado?

Ai pmlm, a consulta deu certo, so ta fantando um detalhe, o row_number é para classificar os devedores, e do jeito que minha consulta está o
primeiro devedor da consulta está com um numero muito alto, a consulta é o seguinte.:

select ROW_NUMBER() over(order by year(ede.data)) as 'CLASSIFICAÇÃO', eee.nome as 'NOME', +'R$ ' +convert(varchar(10),sum(ede.valortot)) as 'TOTAL A PAGAR', case when matcpl.codcur = 1 then 'DIREITO' when matcpl.codcur = 3 then 'MEDICINA' when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO' when matcpl.codcur = 6 then 'NUTRIÇÃO' when matcpl.codcur = 7 then 'ADMINISTRAÇÃO' when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA' end as 'CURSO', max(turma.turma) as 'TURMA', isnull(eee.telaluno,'-') as 'TELEFONE' from eee, matcpl, fl, turma, ede where fl.valorbaixado = 0.0000 and fl.datapag is null and fl.databaixa is null and ede.valorpago = 0 and ede.valortot > 0.00 and ede.datapag is null and matcpl.mataluno = eee.matricula and matcpl.mataluno = eee.mataluno and matcpl.perletivo = eee.perletivo and matcpl.codcur = eee.codcur and turma.matricula = eee.matricula and ede.mataluno = eee.matricula and ede.codlanc = fl.idlan and fl.statuslan in (0) group by eee.nome, year(ede.data), eee.telaluno, matcpl.codcur order by sum(ede.valortot) desc
A classificação tem que aparecer começando com o número 1, que significa em teoria ser o primeiro devedor, porém o resultado dessa query acima é o seguinte.

Rank  |                  NOME                 TOTAL A PAGAR     CURSO           TURMA    TELEFONE
-----------------------------------------------------------------------------------------------------------
254	CARLOS ALBERTO DE SOUSA	                R$  68488.00	BIO	        B1GDA	(89) 9898-474
853	MAURO FURTUNATO PEREIRA	                R$  64107.30	BIO	        B2GDB	-
852	MARCOS CESAR PEREIRA 3           	        R$  57370.50	BIO	        B3GDA	-
6	ALEXANDRE O GRANDE	                        R$  57116.69	BIO	        B4GDA	-
813	THOR                    	                                R$  55395.76	BIO	        B5GDB	-
801	BRITINEY	                                                R$  49224.00	BIO	        B6ADB	-
728	sEYA DE PEGASUS         	                        R$  49224.00	BIO	        B7ADA	-
731	MESTRE ANCIÃO           	                        R$  49224.00	BIO	        B9DBXX	-
750	GOKU                    	                                R$  49224.00	BIO	        B10BDA	-
751	SADAN                                                      R$  49224.00	BIO	        B11ADB	(34) 3888-9999
773	ITACHI                                                      R$  49224.00	BIO	        B12ADA	(61) 3631-2507
581	CLOUD STRIFE             	                        R$  49224.00	BIO	        B13ADB	-

a coluna RANK tinha que aparecer começando com a numeração de 1, e está aparecendo errada!!

Penso que para o que queres basta ter o order by do ROW_NUMBER deve ser igual ao order by do select

Pois é, eu tenho que ordernar pelo total a pagar em ordem decrescente, por que quem ta devendo mais tem que aparecer primeiro na lista…

Ai pmlm, a princípio colocar o Oder By do Select no ROW_NUMBER deu certo, vou fazer mais uns testes qualquer coisa aviso!!

Ai pmlm, a princípio a query ta certa, está aparecendo tuplas repetidas por causa do year(ede.data), se tirar isso aparentemente os registros duplicados desaparecem, mais eu preciso disso por que tenho que mostrar quem ta devendo um valor alto e a data de vendimento for mais antiga, por isso tenho que manter essa data ai, mais se eu manter essa data está me trazendo registros duplicados… ta complicado!!!

Se quiseres o ano mais antigo, min(year(ede.data)) e retiras o year do group by

Quando coloco o min(year(ede.data)) no select não traz o ano mais antigo, tava pensando em coloca-lo no group by, porem, se eu fizer isso meu resultado fica errado!!

Tenho que modificar a query para apresentar o seguinte.: " Vamos supor que tenho um Aluno chamado Augusto Pereira, ele está com uma dúvida de R$ 1500,00 na data de 21/10/2009, e outro aluno chamado Son Goku que está com uma dívida de R$ 2000,00 na data de 12/11/2012"… Minha query vai trazer primeiro o aluno Son Goku por que ele está com uma dívida maior que o aluno Augusto Pereira, porem independente de Augusto Pereira está devendo menos, ele tem que aparecer primeiro por que sua data está menor do que a do aluno Son Goku , sendo assim, tenho que adaptar minha Query para fazer isso!!

Mano to tentando aqui, mais acho que não tem como fazer essa [u]‘Magía’[/u] não!! :evil:

Tenho que aplicar uma regra na minha Query que a seguinte.: " Se a soma total for maior que R$ 3000, tenho que ordenar por data e valor, ou seja a pessoa com a data mais antiga tem que aparecer primeiro, a segunda é, se a soma for menor ou igual R$ 3000, ordernar somente por valor". Agora tenho que bolar uma regra para resolver isso!!

Atirando para o ar seria algo assim:

select row_number(), * FROM
(      select    
          eee.nome                        as 'NOME',   
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',  
            case  
                when matcpl.codcur = 1 then 'DIREITO'  
                when matcpl.codcur = 3 then 'MEDICINA'  
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'  
                when matcpl.codcur = 6 then 'NUTRIÇÃO'  
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'  
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                         
            end as 'CURSO',   
          max(turma.turma)                  as 'TURMA',  
          isnull(eee.telaluno,'-')        as 'TELEFONE'  
    from eee,  
         matcpl,  
         fl,   
         turma,   
         ede  
    where  
         fl.valorbaixado   = 0.0000  
    and fl.datapag is null  
    and fl.databaixa is null    
    and ede.valorpago  = 0  
    and ede.valortot > 0.00  
    and ede.datapag is null    
    and matcpl.mataluno  = eee.matricula  
    and matcpl.mataluno  = eee.mataluno  
    and matcpl.perletivo = eee.perletivo  
    and matcpl.codcur    = eee.codcur  
    and turma.matricula     = eee.matricula   
    and ede.mataluno   = eee.matricula  
    and ede.codlanc    = fl.idlan  
    and fl.statuslan in (0)  
    group by eee.nome,  
              eee.telaluno,  
              matcpl.codcur  
    having sum(ede.valortot) >3000
    order by min(year(ede.data)), sum(ede.valortot) desc  
union
select    
          eee.nome                        as 'NOME',   
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',  
            case  
                when matcpl.codcur = 1 then 'DIREITO'  
                when matcpl.codcur = 3 then 'MEDICINA'  
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'  
                when matcpl.codcur = 6 then 'NUTRIÇÃO'  
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'  
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                         
            end as 'CURSO',   
          max(turma.turma)                  as 'TURMA',  
          isnull(eee.telaluno,'-')        as 'TELEFONE'  
    from eee,  
         matcpl,  
         fl,   
         turma,   
         ede  
    where  
         fl.valorbaixado   = 0.0000  
    and fl.datapag is null  
    and fl.databaixa is null    
    and ede.valorpago  = 0  
    and ede.valortot > 0.00  
    and ede.datapag is null    
    and matcpl.mataluno  = eee.matricula  
    and matcpl.mataluno  = eee.mataluno  
    and matcpl.perletivo = eee.perletivo  
    and matcpl.codcur    = eee.codcur  
    and turma.matricula     = eee.matricula   
    and ede.mataluno   = eee.matricula  
    and ede.codlanc    = fl.idlan  
    and fl.statuslan in (0)  
    group by eee.nome,  
              eee.telaluno,  
              matcpl.codcur  
    having sum(ede.valortot) <=3000
    order by sum(ede.valortot) desc ) 

[quote=pmlm]Atirando para o ar seria algo assim:

select row_number(), * FROM ( select eee.nome as 'NOME', +'R$ ' +convert(varchar(10),sum(ede.valortot)) as 'TOTAL A PAGAR', case when matcpl.codcur = 1 then 'DIREITO' when matcpl.codcur = 3 then 'MEDICINA' when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO' when matcpl.codcur = 6 then 'NUTRIÇÃO' when matcpl.codcur = 7 then 'ADMINISTRAÇÃO' when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA' end as 'CURSO', max(turma.turma) as 'TURMA', isnull(eee.telaluno,'-') as 'TELEFONE' from eee, matcpl, fl, turma, ede where fl.valorbaixado = 0.0000 and fl.datapag is null and fl.databaixa is null and ede.valorpago = 0 and ede.valortot > 0.00 and ede.datapag is null and matcpl.mataluno = eee.matricula and matcpl.mataluno = eee.mataluno and matcpl.perletivo = eee.perletivo and matcpl.codcur = eee.codcur and turma.matricula = eee.matricula and ede.mataluno = eee.matricula and ede.codlanc = fl.idlan and fl.statuslan in (0) group by eee.nome, eee.telaluno, matcpl.codcur having sum(ede.valortot) >3000 order by min(year(ede.data)), sum(ede.valortot) desc union select eee.nome as 'NOME', +'R$ ' +convert(varchar(10),sum(ede.valortot)) as 'TOTAL A PAGAR', case when matcpl.codcur = 1 then 'DIREITO' when matcpl.codcur = 3 then 'MEDICINA' when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO' when matcpl.codcur = 6 then 'NUTRIÇÃO' when matcpl.codcur = 7 then 'ADMINISTRAÇÃO' when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA' end as 'CURSO', max(turma.turma) as 'TURMA', isnull(eee.telaluno,'-') as 'TELEFONE' from eee, matcpl, fl, turma, ede where fl.valorbaixado = 0.0000 and fl.datapag is null and fl.databaixa is null and ede.valorpago = 0 and ede.valortot > 0.00 and ede.datapag is null and matcpl.mataluno = eee.matricula and matcpl.mataluno = eee.mataluno and matcpl.perletivo = eee.perletivo and matcpl.codcur = eee.codcur and turma.matricula = eee.matricula and ede.mataluno = eee.matricula and ede.codlanc = fl.idlan and fl.statuslan in (0) group by eee.nome, eee.telaluno, matcpl.codcur having sum(ede.valortot) <=3000 order by sum(ede.valortot) desc ) [/quote]
Ai pmlm vou tentar aqui mais acho que o ROW_NUMBER precisa do OVER(), por que quando rodei a query me retornou o seguinte erro Incorrect syntax near 'ROW_NUMBER', expected 'OVER'.
Ta ocorrendo uns erros estranhos aqui, não to conseguindo encontra-los
são os seguintes.: Msg 1035, Level 15, State 10, Line 2 Incorrect syntax near 'ROW_NUMBER', expected 'OVER'. Msg 156, Level 15, State 1, Line 41 Incorrect syntax near the keyword 'order'. Msg 102, Level 15, State 1, Line 83 Incorrect syntax near ')'.

Ok, subqueries no sql server precisam de alias.

select row_number() OVER (SELECT 1), t.* FROM  
(      select      
          eee.nome                        as 'NOME',     
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',    
            case    
                when matcpl.codcur = 1 then 'DIREITO'    
                when matcpl.codcur = 3 then 'MEDICINA'    
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'    
                when matcpl.codcur = 6 then 'NUTRIÇÃO'    
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'    
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                           
            end as 'CURSO',     
          max(turma.turma)                  as 'TURMA',    
          isnull(eee.telaluno,'-')        as 'TELEFONE'    
    from eee,    
         matcpl,    
         fl,     
         turma,     
         ede    
    where    
         fl.valorbaixado   = 0.0000    
    and fl.datapag is null    
    and fl.databaixa is null      
    and ede.valorpago  = 0    
    and ede.valortot > 0.00    
    and ede.datapag is null      
    and matcpl.mataluno  = eee.matricula    
    and matcpl.mataluno  = eee.mataluno    
    and matcpl.perletivo = eee.perletivo    
    and matcpl.codcur    = eee.codcur    
    and turma.matricula     = eee.matricula     
    and ede.mataluno   = eee.matricula    
    and ede.codlanc    = fl.idlan    
    and fl.statuslan in (0)    
    group by eee.nome,    
              eee.telaluno,    
              matcpl.codcur    
    having sum(ede.valortot) >3000  
    order by min(year(ede.data)), sum(ede.valortot) desc    
union  
select      
          eee.nome                        as 'NOME',     
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',    
            case    
                when matcpl.codcur = 1 then 'DIREITO'    
                when matcpl.codcur = 3 then 'MEDICINA'    
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'    
                when matcpl.codcur = 6 then 'NUTRIÇÃO'    
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'    
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                           
            end as 'CURSO',     
          max(turma.turma)                  as 'TURMA',    
          isnull(eee.telaluno,'-')        as 'TELEFONE'    
    from eee,    
         matcpl,    
         fl,     
         turma,     
         ede    
    where    
         fl.valorbaixado   = 0.0000    
    and fl.datapag is null    
    and fl.databaixa is null      
    and ede.valorpago  = 0    
    and ede.valortot > 0.00    
    and ede.datapag is null      
    and matcpl.mataluno  = eee.matricula    
    and matcpl.mataluno  = eee.mataluno    
    and matcpl.perletivo = eee.perletivo    
    and matcpl.codcur    = eee.codcur    
    and turma.matricula     = eee.matricula     
    and ede.mataluno   = eee.matricula    
    and ede.codlanc    = fl.idlan    
    and fl.statuslan in (0)    
    group by eee.nome,    
              eee.telaluno,    
              matcpl.codcur    
    having sum(ede.valortot) <=3000  
    order by sum(ede.valortot) desc ) t

[quote=pmlm]Ok, subqueries no sql server precisam de alias.

select row_number() OVER (SELECT 1), t.* FROM  
(      select      
          eee.nome                        as 'NOME',     
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',    
            case    
                when matcpl.codcur = 1 then 'DIREITO'    
                when matcpl.codcur = 3 then 'MEDICINA'    
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'    
                when matcpl.codcur = 6 then 'NUTRIÇÃO'    
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'    
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                           
            end as 'CURSO',     
          max(turma.turma)                  as 'TURMA',    
          isnull(eee.telaluno,'-')        as 'TELEFONE'    
    from eee,    
         matcpl,    
         fl,     
         turma,     
         ede    
    where    
         fl.valorbaixado   = 0.0000    
    and fl.datapag is null    
    and fl.databaixa is null      
    and ede.valorpago  = 0    
    and ede.valortot > 0.00    
    and ede.datapag is null      
    and matcpl.mataluno  = eee.matricula    
    and matcpl.mataluno  = eee.mataluno    
    and matcpl.perletivo = eee.perletivo    
    and matcpl.codcur    = eee.codcur    
    and turma.matricula     = eee.matricula     
    and ede.mataluno   = eee.matricula    
    and ede.codlanc    = fl.idlan    
    and fl.statuslan in (0)    
    group by eee.nome,    
              eee.telaluno,    
              matcpl.codcur    
    having sum(ede.valortot) >3000  
    order by min(year(ede.data)), sum(ede.valortot) desc    
union  
select      
          eee.nome                        as 'NOME',     
          +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL A PAGAR',    
            case    
                when matcpl.codcur = 1 then 'DIREITO'    
                when matcpl.codcur = 3 then 'MEDICINA'    
                when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'    
                when matcpl.codcur = 6 then 'NUTRIÇÃO'    
                when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'    
                when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                           
            end as 'CURSO',     
          max(turma.turma)                  as 'TURMA',    
          isnull(eee.telaluno,'-')        as 'TELEFONE'    
    from eee,    
         matcpl,    
         fl,     
         turma,     
         ede    
    where    
         fl.valorbaixado   = 0.0000    
    and fl.datapag is null    
    and fl.databaixa is null      
    and ede.valorpago  = 0    
    and ede.valortot > 0.00    
    and ede.datapag is null      
    and matcpl.mataluno  = eee.matricula    
    and matcpl.mataluno  = eee.mataluno    
    and matcpl.perletivo = eee.perletivo    
    and matcpl.codcur    = eee.codcur    
    and turma.matricula     = eee.matricula     
    and ede.mataluno   = eee.matricula    
    and ede.codlanc    = fl.idlan    
    and fl.statuslan in (0)    
    group by eee.nome,    
              eee.telaluno,    
              matcpl.codcur    
    having sum(ede.valortot) <=3000  
    order by sum(ede.valortot) desc ) t

[/quote]
Ai pmlm to tentando corririr aqui os seguintes erros que estão acontecendo após a alteração no select colocando o alias

Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'SELECT'. Msg 156, Level 15, State 1, Line 40 Incorrect syntax near the keyword 'order'. Msg 102, Level 15, State 1, Line 82 Incorrect syntax near ')'.

Vamos por partes. Tira a parte do row_number e ve se o “selct from select” funciona.

Ai pmlm, realizando o que vc falou ocorrer os seguintes erros

Msg 1033, Level 15, State 1, Line 42 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified. Msg 102, Level 15, State 1, Line 82 Incorrect syntax near ')'.

Já suspeitava que fosse isso :smiley:

    select row_number() OVER(t.ordem, t.TOTALAPAGAR desc), t.* FROM    
    (      select  min(year(ede.data)) as ORDEM,      
              eee.nome                        as 'NOME',       
              +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTALAPAGAR',      
                case      
                    when matcpl.codcur = 1 then 'DIREITO'      
                    when matcpl.codcur = 3 then 'MEDICINA'      
                    when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'      
                    when matcpl.codcur = 6 then 'NUTRIÇÃO'      
                    when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'      
                    when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                             
                end as 'CURSO',       
              max(turma.turma)                  as 'TURMA',      
              isnull(eee.telaluno,'-')        as 'TELEFONE'      
        from eee,      
             matcpl,      
             fl,       
             turma,       
             ede      
        where      
             fl.valorbaixado   = 0.0000      
        and fl.datapag is null      
        and fl.databaixa is null        
        and ede.valorpago  = 0      
        and ede.valortot > 0.00      
        and ede.datapag is null        
        and matcpl.mataluno  = eee.matricula      
        and matcpl.mataluno  = eee.mataluno      
        and matcpl.perletivo = eee.perletivo      
        and matcpl.codcur    = eee.codcur      
        and turma.matricula     = eee.matricula       
        and ede.mataluno   = eee.matricula      
        and ede.codlanc    = fl.idlan      
        and fl.statuslan in (0)      
        group by eee.nome,      
                  eee.telaluno,      
                  matcpl.codcur      
        having sum(ede.valortot) >3000    
    union    
    select  9999 as ORDEM,      
              eee.nome                        as 'NOME',       
              +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTALAPAGAR',      
                case      
                    when matcpl.codcur = 1 then 'DIREITO'      
                    when matcpl.codcur = 3 then 'MEDICINA'      
                    when matcpl.codcur = 5 then 'SISTEMAS DE INFORMAÇÃO'      
                    when matcpl.codcur = 6 then 'NUTRIÇÃO'      
                    when matcpl.codcur = 7 then 'ADMINISTRAÇÃO'      
                    when matcpl.codcur = 8 then 'EDUCAÇÃO FÍSICA'                             
                end as 'CURSO',       
              max(turma.turma)                  as 'TURMA',      
              isnull(eee.telaluno,'-')        as 'TELEFONE'      
        from eee,      
             matcpl,      
             fl,       
             turma,       
             ede      
        where      
             fl.valorbaixado   = 0.0000      
        and fl.datapag is null      
        and fl.databaixa is null        
        and ede.valorpago  = 0      
        and ede.valortot > 0.00      
        and ede.datapag is null        
        and matcpl.mataluno  = eee.matricula      
        and matcpl.mataluno  = eee.mataluno      
        and matcpl.perletivo = eee.perletivo      
        and matcpl.codcur    = eee.codcur      
        and turma.matricula     = eee.matricula       
        and ede.mataluno   = eee.matricula      
        and ede.codlanc    = fl.idlan      
        and fl.statuslan in (0)      
        group by eee.nome,      
                  eee.telaluno,      
                  matcpl.codcur      
        having sum(ede.valortot) <=3000) t  
order by t.ordem, t.TOTALAPAGAR desc