Mounting a sql query by filtering data

1

I am trying to mount a report, where I need to list deleted documents, I have the following sql statement:

SELECT id,nf,status,data FROM documentos

For example I have the following results:

Whenyou'rereadytheexcluded,itgivesmethefollowingresult:

SELECTid,nf,status,dataFROMdocumentosWHEREstatusLIKE('%EXCLUIDO%')

But I should not consider the document whose nf is 000002, because it was listed next, so it can not appear in the sql result, it should only show nf 000001.

Could anyone help me?

    
asked by anonymous 31.08.2017 / 17:01

7 answers

1

Use not not to check NFs that have more than one status.

SELECT id,nf,status,data 
FROM documentos d1
WHERE status LIKE ('%EXCLUIDO%')
and not exists (SELECT 1 FROM documentos d2 
                         where d1.nf = d2.nf 
                         and d2.status <> d1.status)
    
01.09.2017 / 21:38
1
SELECT id,nf,status,data FROM documentos WHERE status = 'EXCLUIDO' and NF <> '000002'

I put the status with the = sign because the query gets lighter without using like.

    
31.08.2017 / 17:06
0
SELECT id, nf, status, data 
FROM documentos 
WHERE status = EXCLUIDO' 
  and nf not in ('000002')

As its status field will always be "EXCLUDED" , when it is not to be displayed, make a comparison of equality, instead of like in where will do with that his quest is more performative.

In the nf constraint, you can add the nf according to your needs, for example: nf not in ('000002','000003','000004') , but I believe that with% new nf will be added in this clause, so it would be better to have% some type of field or even another table referencing these nf , not to leave them stays in your query.

    
31.08.2017 / 17:37
0

You need to filter the items with status "EXCLUDED" (as you already do) and also with nf

SELECT id, nf, status, data 
FROM documentos 
WHERE status LIKE ('%EXCLUIDO%') 
  and nf <> '000002'

edited after comment

In case of invalid nf list, the query would need to be changed to use NOT IN as below:

SELECT id, nf, status, data 
FROM documentos 
WHERE status LIKE ('%EXCLUIDO%') 
  nf NOT IN ('000002', '000003', '000003')
    
31.08.2017 / 17:06
0

If I understood correctly, I think with Except I could solve your problem:

create table #ttt1 (
    id int
    ,nf int
    ,status varchar(50)
    ,data datetime
)

insert into #ttt1 values
(1,1,'excluido',getdate()),
(2,2,'excluido',getdate()),
(3,2,'relacionado',getdate()+1)

select nf from #ttt1 t1 where status = 'excluido'
except
select nf from #ttt1 t1 where status = 'relacionado'

It will return only the NF that has no related

    
31.08.2017 / 19:04
0

Table used

SQL

SELECTid,nf,status,data,count(NF)ascFROMdocumentosgroupbyNFhavingc=1

Result

  

Thesameresultisobtainedwiththequerybelow

SELECTid,nf,status,dataFROMdocumentosgroupbyNFhavingcount(NF)=1

HAVING clause

    
01.09.2017 / 21:05
-2

SELECT id, nf, status, data FROM documents WHERE STATUS = 'EXCLUDED'

    
31.08.2017 / 17:39