如何汇总不同的值?

时间:2014-12-23 05:26:15

标签: mysql sql

+---+------------+
|sid| discounts  | 
+---+------------+
| 1 | 10.00      |
| 2 | 20.00      |
  2 | 20.00      |
+---+------------+

我需要获得列折扣的总和,但是如果列sid具有相同的值,则只添加一行而不是全部。

所以我需要说30.00而不是50.00

我试过这样的事情

 SELECT DISTINCT sid FROM (SELECT SUM(discounts) FROM $table_name)

SELECT SUM(discounts) FROM $table_name WHERE sid IN (SELECT DISTINCT 'sid' FROM $table_name)

我刚刚收到您的SQL语法错误'

5 个答案:

答案 0 :(得分:2)

如果您删除single quuto betwwen sid

,则第二个查询将有效
SELECT SUM(discounts) FROM $table_name WHERE sid IN (SELECT DISTINCT sid FROM $table_name)

答案 1 :(得分:0)

select sum(discounts) from (select discounts,sid  from $table_name group by sid) t

答案 2 :(得分:0)

我希望这会起作用

$sql=mysql_query("select SUM(discounts) from table_name groub by sid");

答案 3 :(得分:0)

它很简单,你可以使用

select SUM(discount) from (SELECT discount FROM  `table_name` group by sid) as discount

希望这对您有用

答案 4 :(得分:0)

您可以尝试以下SQL:

select 
    sum(t.discount) 
from 
    (select 
        distinct sid, discount 
    from 
        $table_name
    ) t

DEMO