views:

86

answers:

4

Hello to all!

I have a sql statement like this:

select a.id, a.valfrom ...
  inner join ...
  where ...;

As a result I have this:

id    val
---------
 3     10
 3     10
 3     10
 9     21
 9     21
11      2
11      2
13     30

So you can see, one id has one value.

If I do a group by (a.id), I get:

id    val
---------
 3     10
 9     21
11      2
13     30

What I want to get of the last result is the sum: 10+21+2+30 = 63.

So how can I get the sum as a single result? If I do a sum(a.val) and use group by (a.id) I do not get 63, I get the sum for every id, for example id=3 -> 10+10+10 = 30.

Best Regards.

+3  A: 

You don't want a GROUP BY, then. You also can't select the ID correctly in standard SQL. You just want:

SELECT SUM(val) FROM (SELECT DISTINCT id, val FROM ...) AS foo

But, MySQL supports a few extensions to standard SQL syntax which MIGHT make this work:

SELECT DISTINCT id, SUM(val) FROM ...

Borealid
Select from select equals "boooooo".Grouping by is the way, but with something they all have in common: the `NULL`. See my answer
Bogdan Constantinescu
I did this and I get the error message:"Every derived table must have its own alias"
Tim
@Tim: edited, easy fix
Borealid
I solved it. I have to use AS for the subselected table and AS for "id" and "val" in the subselect
Tim
A: 

Using a subselect and distinct:

  select sum(valform) from (
    select distinct a.id, a.valfrom ...
    inner join ...
    where ...
  )

Or using group-by:

  select sum(valform) from (
    select a.id, min(a.valfrom)
    inner join ...
    where ...
    group by a.id
  )

But I reckon the first query will be faster.

inflagranti
@inflagranti: technically, in standard SQL you must GROUP on all columns which are not aggregates, if memory serves correctly... MySQL doesn't enforce the restriction for some reason, though.
Borealid
without group by, I get the result as you can see in my first post. That is not the result I want to have.
Tim
Yes, I misread your question first, see new solution.
inflagranti
@Borealid: You are correct - [MySQL documented the "feature"](http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html); IIRC, SQLite has the same GROUP BY functionality as MySQL (grrrr...)...
OMG Ponies
A: 

This will do the trick :)

select a.id, a.valfrom, SUM(val) as mySum ...
  inner join ...
  where ...
GROUP BY NULL
Bogdan Constantinescu
What if two different IDs have the same value?
Borealid
This results in the same thing as Borealid's DISTINCT example, but it's less clear.
Marcus Adams
A: 

If you query is

select a.id, a.valfrom ...
  inner join ...
  where ...;

try this:

select sum(distinct a.valfrom)
  inner join ...
  where ...;

No "group by", hands down.

ceteras