H
H
hesebif7242020-02-04 03:48:46
SQL
hesebif724, 2020-02-04 03:48:46

How to calculate the sum of unique values?

Good day!
How to calculate the sum of unique values ​​for any column, taking only the first value?
For example, take only the first value by id_j, sort by rowid. Tried through distinct .. But not even

id_h|id_j|cost
1|2|15
2|2|5
3|1|20
1|4|100
3|2|3

To end up
with id_h|cost
1|115
3|20

addition of 1 and 4 entries, 3 entry. this is how it turns out. Records 2 and 5 are ignored due to the repetition of 2 in id_j
roughly speaking, we ignore all records when id_j is repeated. because of this, wherever in the records there are 2 in id_j are ignored. and three entries remain, which we summarize

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
idShura, 2020-02-04
@hesebif724

addition of 1 and 4 records, 3 records. this is how it turns out.
roughly speaking, we ignore all entries when repeating id_j. because of this, wherever in the records there are 2 in id_j are ignored. and three entries remain, which we summarize

Try like this:
SELECT A.ID_H,
       SUM(A.COST) COST
  FROM (SELECT ID_H,
               ID_J,
               COST,
               RANK() OVER(PARTITION BY ID_J ORDER BY ID_H ASC) RNK
          FROM MYTABLE
       ) A WHERE A.RNK = 1
 GROUP BY A.ID_H

You can check online here
Query output result
5e38f227bc844824225817.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question