Campos no Select mais não no Group By

70 respostas
A

Bom dia galera, to precisando fazer uma parada aqui na minha consulta mais não sei se da certo, tenho que colocar um campo para aparecer no select, mais quando coloco ele me retorna um erro falando que precisar se colocado também no Group by, por causa de uma soma que fiz com outro campo, para minha minha query ficar certa, esse campo tem que aparecer no select mais não no Group By, tem como fazer isso??

70 Respostas

drsmachado

Qual banco de dados você utiliza?

Aleksandro

Tenta assim … deve resolver o seu problema:

select coluna1. coluna2, total from (
select coluna1, coluna2, sum(coluna3 + coluna4) as total from tabela group by coluna1, coluna2 coluna3, coluna4 );

A

Estou usando SQLServer 2005…

A

Aleksandro:
Tenta assim … deve resolver o seu problema:

select coluna1. coluna2, total from (
select coluna1, coluna2, sum(coluna3 + coluna4) as total from tabela group by coluna1, coluna2 coluna3, coluna4 );


Boa tarde, não entendi muito bem como fazer, tem como vc me da um exemplo usando minha query?

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', //turma.codtur as 'TURMA', // <-- TENHO QUE COLOCAR ESSA LINHA isnull(ealunos.telaluno,'-') as 'TELEFONE' from eee, mtcpl, //turma, // <-- TENHO QUE COLOCAR ESSA LINHA 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 //turma.codtur // <-- ISSO NÃO PODE APARECER AQUI..

pmlm

Uma pergunta simples:

Se colocares a turma no GROUP BY vais ter registos repetidos com a turma diferente, certo?

1 João 1000 DIREITO turma1 999999999
2 João 1500 DIREITO turma2 999999999

E tu queres algo assim

1 João 2500 DIREITO ??? 999999999

Mas neste caso, o que deve aparecer em ???

A

pmlm:
Uma pergunta simples:

Se colocares a turma no GROUP BY vais ter registos repetidos com a turma diferente, certo?

1 João 1000 DIREITO turma1 999999999
2 João 1500 DIREITO turma2 999999999

E tu queres algo assim

1 João 2500 DIREITO ??? 999999999

Mas neste caso, o que deve aparecer em ???

Sim, o que eu quero é esse resultado que você transcreveu ai acima, pois é, o solicitado é isso ai mesmo, somar o total de cada pessoa, independente se ele está em outras turmas, no pontos de interrogação, tem que aparecer a turma, mais ai tem um problema, se o cara está em duas turmas, o seu total irá aparecer em qual turma???
Como no seu exemplo ele está em 2 turmas, o total dele pode ser vinculado a qualquer turma!!

pmlm

se é em qq turma, basta por no select, por exemplo,

A

pmlm:
se é em qq turma, basta por no select, por exemplo,


Ai mano, inserir o MAX, agora deu outro probleminha, a soma veio errada… =/

Aleksandro

Anderson S.:
Aleksandro:
Tenta assim … deve resolver o seu problema:

select coluna1. coluna2, total from (
select coluna1, coluna2, sum(coluna3 + coluna4) as total from tabela group by coluna1, coluna2 coluna3, coluna4 );


Boa tarde, não entendi muito bem como fazer, tem como vc me da um exemplo usando minha query?

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', //turma.codtur as 'TURMA', // <-- TENHO QUE COLOCAR ESSA LINHA isnull(ealunos.telaluno,'-') as 'TELEFONE' from eee, mtcpl, //turma, // <-- TENHO QUE COLOCAR ESSA LINHA 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 //turma.codtur // <-- ISSO NÃO PODE APARECER AQUI..

Tá estranho este select , você quer trazer a coluna turma.codtur , porém ela não liga com ninguém … tá certo este select …

No oracle , faria um subselect ligando com a tabela turma , no MS deve dar para fazer também …

A

Aleksandro:
Anderson S.:
Aleksandro:
Tenta assim … deve resolver o seu problema:

select coluna1. coluna2, total from (
select coluna1, coluna2, sum(coluna3 + coluna4) as total from tabela group by coluna1, coluna2 coluna3, coluna4 );


Boa tarde, não entendi muito bem como fazer, tem como vc me da um exemplo usando minha query?

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', //turma.codtur as 'TURMA', // <-- TENHO QUE COLOCAR ESSA LINHA isnull(ealunos.telaluno,'-') as 'TELEFONE' from eee, mtcpl, //turma, // <-- TENHO QUE COLOCAR ESSA LINHA 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 //turma.codtur // <-- ISSO NÃO PODE APARECER AQUI..

Tá estranho este select , você quer trazer a coluna turma.codtur , porém ela não liga com ninguém … tá certo este select …

No oracle , faria um subselect ligando com a tabela turma , no MS deve dar para fazer também …


O Select ta certo, por que o relacionamento da tabela ‘turma’ acontece exatamente nas linhas 32 e 33, // and mtcpl.perletivo = turma.codperlet //and mtcpl.codcur = turma.codcur, até ai tudo bem, a turma está vindo corretamente, o único porém é que se não coloca-la no group by, me volta um erro solicitando a inserção da mesma no group by, e se coloca-la no group by, meu resultado fica todo errado, por que abrir esse post solicitando se tem como colocar um valor no select sem que ele esteja no group by…

A

pmlm:
se é em qq turma, basta por no select, por exemplo,


Outro porém em relação ao MAX, é que se inserir esse comando no campo turma.codtur, ele traz a maior turma, ou seja, vai trazer a mesma turma para todos os alunos, se tiver um aluno vinculado a 2 ou mais turma, tenho que mostrar o total a pagar desse aluno, e a turma pode ser qualquer uma, desde que está esteja vinculada a ele, como no exemplo que você inseriu ai acima, para João tanto faz listar a turma1 ou a turma2, o importante é a soma do seu total está correto e aparecer na lista uma das turmas vinculadas a ele…

pmlm

O MAX vai trazer a “maior” turma para o aluno em causa. A soma não tem em conta a turma já que não está agrupado por turma e soma para todas as turmas, que penso que é o que pretendes.

A

Pois é cara muito estranho isso mesmo, está trazendo uma turma para todos as linhas da consulta, e a soma está aparecendo errada!!
=/

pmlm

Como está o teu select?

A

O Select é esse citado ai acima…

pmlm

E descomentaste as linhas dos “and” da tabela turma?

A

Se descomentar as linhas referentes a tabela turma, vai pedir pra colocar esse campo no Group by, colocando o mesmo no group by a soma total de débito fica totalmente errada!!
Por isso que abrir o tópico perguntando se tem como colocar um campo no Select sem coloca-lo no group by…

A

Existe alguma função STRING que eu possa utilizar para tentar “Burlar” o SQLServer para não pedir a inclusão do campo no Group By ???

A

Se o campo da turma não estivesse no group by, tenho certeza que a consulta dava certo!!

pmlm

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
A

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…

pmlm

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?

A

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	([telefone removido]
773	ITACHI                                                      R$  49224.00	BIO	        B12ADA	([telefone removido]
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!!

pmlm

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

A

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

A

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

A

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!!!

pmlm

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

A

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!!

A

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!!

A

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

A

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!!

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 )
A

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 )


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 ')'.

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
A

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


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 ')'.

pmlm

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

A

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 ')'.

pmlm

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
A

Ai pmlm após a inserção da sua query está aparecendo os seguinte erros Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '.'. Msg 102, Level 15, State 1, Line 80 Incorrect syntax near ')'. , mais antes eu queria que vc me explica-se as linhas de códigos

E

pmlm

Para os registos com total > 3000 devolve o ano, porque primeiro queres ordernar por ano. Para os outros devolve 9999 como ano porque queres que apareçam depois.

Em relação aos erros não estou a ver motivo para eles agora, tenta fazer novamente sem o row_number para tentar despistar onde estará o erro.

A
Ai pmlm, eu conseguir reduzir a princípio os erros para 1 só com a seguinte query.:
select row_number() OVER(t.ordem, t.TOTAL desc) FROM    
    (      select  min(year(ede.data)) as ORDEM,      
              eee.nome                        as 'NOME',       
              +'R$  ' +convert(varchar(10),sum(ede.valortot))      as 'TOTAL',      
                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 &gt; 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) &gt;3000)    
   UNION
     
   ( select  9999 as ORDEM,      
              eee.nome                        as 'NOME',       
              +'R$  ' +convert(varchar(10),sum(ede.valortot))              as 'TOTAL',      
                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 &gt; 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) &lt;=3000)  
order by t.ordem, t.TOTAL desc
o único erro que ta aparencendo agora é esse
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
pmlm

Falta o alias para os inner selects

Põe os dois select entre parêntesis e o t no fim.

A

pmlm:
Falta o alias para os inner selects

Põe os dois select entre parêntesis e o t no fim.


To tentando inserir os parenteses aqui nos select’s mais não ta dando, como ficaria?-

pmlm

Assim dá erro?

select t.* FROM      
    (      select  min(year(ede.data)) as ORDEM,        
              eee.nome                        as 'NOME',         
              +'R$  ' +convert(varchar(10),sum(ede.valortot))      as 'TOTAL',        
                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 'TOTAL',        
                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.TOTAL desc
A

Ai pmlm como vai ser relatório pensei melhor, vou fazer 2 consultas diferentes, a primeira consulta vai mostrar os alunos que devem mais de 3000 reais ordenados por ede.data e sum(ede.valor) e a outra os alunos que devem menos de 3000 reais ordenaos por sum(ede.valor)… não preciso mostrar tudo numa query so… tem como vc me ajudar??

pmlm

Assim é só separar os dois selects que estão no FROM…

A

pmlm:
Assim é só separar os dois selects que estão no FROM…


Entendi vou tentar fazer aqui, só um detalhe, tem como substutuir aquele 9999 do select por outra coisa?

pmlm

Se vais separar já não precisas sequer disso.

A

Ai pmlm após separar as querys executei primeiro a que vai ordenar por DATA(min(ede.data)) e por VALOR ( sum(ede.valortot)), porém me deparei com um resultado errado, como a primeira ordenação é pela data minima, tem que aparecer em primeiro plano o cara que tava com a data menor, e isso não está acontecendo, as datas estão aparecendo aleatóriamente… o resultado da query ta assim…


LINICKER está com a data 05/03/2009, e FLÁVIA LUCIA está com a data 09/02/2009, porem LINICKER está aparecendo primeiro do que ela, como a data dela é menor, ela tem que aparecer primeiro, se vc analisar melhor a imagem vai ver que isto está divergente, e está errado… to tentando corrigir aqui, tem alguma sugestão?
A Query é a seguinte

select ROW_NUMBER() over(order by min(ede.data),sum(ede.valortot)) as 'CLASSIFICAÇÃO', eee.nome as 'NOME', min(convert(char(10),ede.data,103)) as 'DATA', +'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(ee.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 = ede.mataluno and matcpl.perletivo = ede.perletivo and matcpl.codcur = ede.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, eeee.telaluno, matcpl.codcur having sum(ede.valortot) > 3000 order by min(ede.data),sum(ede.valortot)

pmlm

Muda

para

Tu queres a menor data e não a menor conversão da data (nota que são coisas diferentes)

A

pmlm:
Muda

para

Tu queres a menor data e não a menor conversão da data (nota que são coisas diferentes)

Ai pmlm, a princípio deu certo, vou modificar a segunda query, eu acho que vou ter problemas depois em juntar os dois selects no relatório pelo seguinte fato.: o Row_number do primeiro select vai trazer o rank dos alunos devedores com a dívida maior que 3000, o Row_number do segundo select também vai trazer o rank dos alunos devedores menor que 3000, porem, ao juntas esses dois select’s no relatório, após mostrar o ultimo registro dos alunos devedores do primeiro select, vai mostrar os alunos devedores do segundo select iniciando o rank como ‘1’, sendo que na verdade tinha que proseguir com a contagem… =/

Tenho que pensar numa forma para resolver isso!!

pmlm

Como geras o relatório? Isso é um contador, deve haver maneira muito fácil de fazer isso sem ser no SQL.

A

Ai mano bom dia como vai?
Me falaram pra mim fazer essa consulta por UNION… como sería??

pmlm

O UNION era como eu já tinha feito atrás, com dois selects unidos.

A

Entendi, vou fazer dessa maneira, só to vendo a questão do Row_number do segundo select, que vc colocou para aparecer 9999,

A
pmlm:
O UNION era como eu já tinha feito atrás, com dois selects unidos.
Ai mano, eu fiz a união das query de uma maneira diferente aqui que ficou como eu queria, só tem um porém, é quando inicia os dados do segundo select a classificação começa do 1º novamente, e o certo sería continuar, to tentando arrumar uma forma aqui... o select ficou o seguinte.:
select  
      ROW_NUMBER() over(order by  min(ede.data),sum(ede.valortot) desc) 
                                          as 'CLASSIFICAÇÃO',
      eee.nome                        as 'NOME', 
      convert(char(10),min(ede.data),103) as 'DATA',
      +'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  = ede.mataluno
 and matcpl.perletivo = ede.perletivo
 and matcpl.codcur    = ede.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 ALL

select  
      ROW_NUMBER() over(order by sum(ede.valortot)desc) 
                                          as 'CLASSIFICAÇÃO',
      eee.nome                        as 'NOME', 
      convert(char(10),min(ede.data),103) as 'DATA',
      +'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  = ede.mataluno
 and matcpl.perletivo = ede.perletivo
 and matcpl.codcur    = ede.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
pmlm

Experimenta o primeiro select que está nesta página.

A

Pois é pmlm, esse select que postei ai é um aprimoramento do que vc postou, no teu select, o segundo select do union aparece 9999 para “Rank”, sendo que tinha que continuar a classficação do primeiro select…

pmlm

Sim, mas no meu tenho um outro select fora e o row_number é só nesse que está, para que a numeração seja continuada

A

pmlm:
Sim, mas no meu tenho um outro select fora e o row_number é só nesse que está, para que a numeração seja continuada

Ai mano pensei melhor vou utilizar sua query mesmo :D, dei uma analisada aqui ela ta melhor estruturada do que a que modifiquei vou ficar com ela mesma 8) , eu só queria modificar esse parametro 9999 do segundo select para continuar as ocorrencias de ordenação, será que tem como?

pmlm

Como tens a query neste momento e que resultados devolve?

A
pmlm:
Como tens a query neste momento e que resultados devolve?
Pois é, é basicamento o que te expliquei acima, tou postar uma imagem pra vc ver, o que to querendo resolver é o seguinte, apartir o segundo select o ROW_Number está começando do 1º de novo, tenho que arrumar isso.. A QUERY É ESSA
select  
      ROW_NUMBER() over(order by  min(ede.data),sum(ede.valortot) desc) 
                                          as 'CLASSIFICAÇÃO',
      eee.nome                        as 'NOME', 
      convert(char(10),min(ede.data),103) as 'DATA',
      +'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  = ede.mataluno
 and matcpl.perletivo = ede.perletivo
 and matcpl.codcur    = ede.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 ALL

select  
      ROW_NUMBER() over(order by sum(ede.valortot)desc) 
                                          as 'CLASSIFICAÇÃO',
      eee.nome                        as 'NOME', 
      convert(char(10),min(ede.data),103) as 'DATA',
      +'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  = ede.mataluno
 and matcpl.perletivo = ede.perletivo
 and matcpl.codcur    = ede.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

[img]http://i45.tinypic.com/bhnjmf.jpg[/img]

pmlm
SELECT  ROW_NUMBER() over (ordenacao, TOTALAPAGAR desc) as 'classificação, t.*
FROM
(select    
        min(ede.data) as ordenacao,  
      eee.nome                        as 'NOME',   
      convert(char(10),min(ede.data),103) as 'DATA',  
      +'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  = ede.mataluno  
and matcpl.perletivo = ede.perletivo  
and matcpl.codcur    = ede.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 ALL  
  
select    
     9999 as ordenacao,
      eee.nome                        as 'NOME',   
      convert(char(10),min(ede.data),103) as 'DATA',  
      +'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  = ede.mataluno  
and matcpl.perletivo = ede.perletivo  
and matcpl.codcur    = ede.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
A

Ao executa ess auqery sugeria por vc, aparece o seguinte erro

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ','. Msg 102, Level 15, State 1, Line 83 Incorrect syntax near 't'.

pmlm

Ok, última tentativa. Aparentemente isso está bem excepto pela ausência do AS no alias da sub query.

Na última linha, em vez de

coloca

A

[quote=pmlm]Ok, última tentativa. Aparentemente isso está bem excepto pela ausência do AS no alias da sub query.

Na última linha, em vez de

coloca

O erro persiste…

A

Ta osso essa query…

pmlm

Não faço a mínima ideia do que possa ser o problema agora.

A

Batendo um olho na sua query, eu vi que na primeira linha está assim:

as 'classificação, t.*

Você deveria fechar essa aspa simples.

Criado 28 de janeiro de 2013
Ultima resposta 15 de fev. de 2013
Respostas 70
Participantes 5