Doubt - SQL Server - Using Union

Asked

Viewed 40 times

1

Guys, I got the following Union:

select cgc, item, matricula, cota, dataInicio, dataFim 
from [dbo].[cotas] as t1 
where dataFim is null
union
select cgc, item, matricula, cota, dataInicio, dataFim 
from [dbo].[cotas] as t2 
where dataInicio >='01/05/2019' and dataFim<='31/05/2019'

só que eu preciso fazer um resultado final... em que t1.cgc seja diferente de t2.cgc

It turns out that when the Fim date is null, it means that the quota is active. And when it is filled in, the quota is inactive. An employee may have inactive quotas in the CGC that currently works, but there is no way to have active quotas in a CGC that has already worked and no longer works. Only that the employee (enrollment) may have worked in more than one CGC in the same month. I need to take all quotas that are active. And, just take the inactive ones that are from a cgc that he worked on previously.

Does anyone know how to do this with Union? Or should I do it another way? Thank you.

  • I couldn’t understand your explanation, what is the outcome you expect to return? You want all active CGC accounts that would be the accounts where Im is null and inactive accounts that have the dataFim is not null and t2,cgc not in (SELECT t1.cgc from [dbo]. [quotas] WHERE Where dataFim is null).

1 answer

0


From what you explained you want to take the data as many Active as inactive, you can give an active CGC subquery and perform a inner join in Inactive, the problem is that it will return all inactive quotas of an active employee. Since you need columns to be displayed without duplicity maybe this option is the best.

select 
    t1.* 
from 
    [dbo].[cotas]
where 
    dataFim is null
UNION
select
    t2.*
from 
    [dbo].[cotas] as t2 
    inner join (
        select cgc, item, matricula, cota, dataInicio, dataFim 
        from [dbo].[cotas]
        where dataFim is null) as t3 on t3.cgc <> t2.cgc 
where t2.dataInicio >='01/05/2019' and t2.dataFim<='31/05/2019'

See if this query solves your problem.

  • It almost solves... only it’s actually with the t1.cgc<>t2.cgc... but anyway, when I do Join... it duplicates all the columns and I needed the results listed row by row, with the columns individualized.... like what Union does

  • Good in this way that you describe better perform a query for the unfinished ones with a Union of a second query added from an Inner Join to a third query identical to the first, see the above sql it was changed

  • It worked, that’s right!!! Thank you!!!!

Browser other questions tagged

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