SQL Server Grouping Conditionally

Asked

Viewed 33 times

0

I have the following problem.

I have a relationship between 2 tables (1)Tb_log_relac_nfs and (2)Tb_fat_notafiscal_item.

Table 2 is where I write both input and output notes.

1 is one that stores the reference of the output notes with the input notes.

I keep this reference because I work with the concept of balance consumption, that is, all my outgoing notes must consume the amount of some incoming note.

An output note can consume more than one input note. An input note has an operating code and I can refer to it in an output note input notes with different codes of operation.

My problem is precisely in these cases. If the operation codes are 2502,1501,1502,2501 I need to mark a new field as "S", if not these codes it needs to be "N", however, if there is an output note with more than one code, I need to mark it as "S" as well.

I tried to make a Count inside the case but it didn’t help me much.

That was the query I got so far

>  select
>     rl.CD_Empresa, 
>     rl.Nr_LanctoFiscal_Saida,
>     rl.ID_NFItem_Saida, 
>     ST_RE = CASE WHEN NIC.CD_CFOP IN (2502,1501,1502,2501) THEN 'S' 
>             WHEN  (select COUNT(*)
>                 from TB_LOG_Relac_NFs aarl
>                 join TB_FAT_NotaFiscal_Item aanic on aarl.Nr_LanctoFiscal_Entrada=aanic.Nr_LanctoFiscal and
> aanic.ID_NFItem=aarl.ID_NFItem_Entrada
>                 join TB_FAT_NotaFiscal_Item aanil on aarl.Nr_LanctoFiscal_Saida=aanil.Nr_LanctoFiscal and
> aanil.ID_NFItem=aarl.ID_NFItem_Saida
>                 where  aarl.Nr_LanctoFiscal_Saida=rl.Nr_LanctoFiscal_Saida and
> aarl.ID_NFItem_Saida=rl.ID_NFItem_Saida) >1 THEN 's'
>     ELSE 'N' END,
>     sum(rl.QTD_Relacinada) QTD_Relacinada from TB_LOG_Relac_NFs rl join TB_FAT_NotaFiscal_Item nic on
> rl.Nr_LanctoFiscal_Entrada=nic.Nr_LanctoFiscal and
> nic.ID_NFItem=rl.ID_NFItem_Entrada join TB_FAT_NotaFiscal_Item nil on
> rl.Nr_LanctoFiscal_Saida=nil.Nr_LanctoFiscal and
> nil.ID_NFItem=rl.ID_NFItem_Saida where   nil.Nr_LanctoFiscal=59725
> group by
>     rl.CD_Empresa, 
>     rl.Nr_LanctoFiscal_Saida,
>     rl.ID_NFItem_Saida,
>     NIC.CD_CFOP

And the result continues in two lines:

inserir a descrição da imagem aqui

  • 1

    In your "group by" what does NIC.CD_CFOP stand for? Missing by ST_RE field

  • 1

    Thought of a Function ? Another solution could be a column in Tb_log_relac_nfs powered by triggers

  • 1

    manually adds even the expected result? do not draw right as should be the result.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.