Home > OS >  Distinct sum of a dataset
Distinct sum of a dataset

Time:12-01

I have a dataset like this :

TYPE count
TYPE1 50
TYPE2 20
TYPE1 10
TYPE2 30

i want to sum the distinct type in a same line :

TYPE count
TYPE1 60
TYPE2 50

Can you help me please ?

Thanks

CodePudding user response:

You seem to need a basic aggregation query:

SELECT TYPE, SUM(count) AS count
FROM yourTable
GROUP BY TYPE;

CodePudding user response:

What you'll want to use is GROUP BY combined with an aggregate function, SUM() for a table.

Say you have a table, simply defined as

CREATE TABLE dataset(type varchar(50), cnt int);

with the dataset you provided:

INSERT INTO dataset (type, cnt)
VALUES
  ('TYPE1', 50),
  ('TYPE2', 20),
  ('TYPE1', 10),
  ('TYPE2', 30)

That'll allow you to query as such:

SELECT type, SUM(cnt)
FROM dataset
GROUP BY type

See also SQLFiddle: http://sqlfiddle.com/#!9/7edf02/2/0

  •  Tags:  
  • sql
  • Related