Select Distinct in only one of the tables

Asked

Viewed 174 times

0

I have the following separate tables, A and B which I am placing next to each other to facilitate:

+--------------+------------+-------------+
|ID Relacional |     A      |      B      |
+--------------+------------+-------------+
| 35           | 30         | 28          |
| 20           | 10         | 4           |
| 20           | 10         | 5           |
+--------------+------------+-------------+

I need to create a code that divides the value of B by the value of A.

Example: 1st line: 28/30.

But when the Relational ID is repeated, I need to divide only one value of A by the sum of the value of B.

Example: 2nd and 3rd row: 10 / (5 + 4)

My current code:

select
sum(A.valorA) as ColunaA,
sum(B.valorB) as ColunaB,
sum(B.valorB) /sum(A.valorA) as Resultado

from tableA A, tableB B where A.id = B.id
group by ...
order by ...

The resulting table is

+--------------+------------+-------------+
|  ColunaA     |  ColunaB   |   Resultado |
+--------------+------------+-------------+
| 30           | 28         | 0.93        |
| 10           | 4          | 0.45 (9/20) |
| 10           | 5          |             |
+--------------+------------+-------------+

1 answer

1

Now see if it helps you :)

declare @tmp table(
    [ID] int,
    [A] int,
    [B] int
)

insert into @tmp values (35, 30, 28)
insert into @tmp values (20, 10, 4 )
insert into @tmp values (20, 10, 5 )


 -- resultados com ID unico
select
    ID,
    max(A) AS A,
    max(B) AS B,
    sum(B) / cast(sum(A) as float) as Resultado
from @tmp 
group by ID
having count(ID) = 1

union

-- Resultados com multiplos IDs
--join para apresentar todos os ids repetidos
select 
    t1.ID, 
    t1.A, 
    t1.B, 
    t2.Resultado
from @tmp t1
inner join (
    select
    ID, 
    max(A) AS A,
    sum(B) AS B,
    sum(B) / cast(sum(A) as float) as Resultado
    from @tmp 
    group by ID
    having count(ID) > 1
) as t2 on  t1.ID = t2.ID

Browser other questions tagged

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