用于对唯一字段对求和的SQL语句

时间:2013-08-13 14:33:31

标签: mysql sql

我有一个像这样的表:

  country  |city     |sales | old
  -------------------------------
    USA    | New York|  100 |   1
    USA    | New York|  200 |   0
    USA    | Miami   |   50 |   1
    Canada | Toronto |   20 |   0
    Canada | Toronto |  100 |   0

我想做两件事:

1)我想产生这样的结果,即所有国家/城市对的所有销售额的总和:

  country  |city     |sales|
  --------------------------
    USA    | New York|  300|
    USA    | Miami   |   50|
    Canada | Toronto |  120|

2)我想产生这样的结果,仅在新账户上的唯一国家/城市对的所有销售总和(old = 0)

  country  |city     |sales|
  --------------------------
    USA    | New York|  200|
    Canada | Toronto |  120|

我需要2个SQL语句吗?它目前超出了我的新SQL技能......

P.S。如果我想做与#2相反的事情,那么总结旧帐户(这么老!= 0),然后我将如何更改#2的SQL语句

2 个答案:

答案 0 :(得分:2)

您可以使用CASE语句(SQL版本的IF..THEN)在一个查询中完成所有操作。

SELECT  Country
        ,City
        ,SUM(Sales) as Tot_Sales 
        ,SUM( CASE WHEN Old = 0 THEN 0 ELSE Sales END) as New_Sales
        ,SUM( CASE WHEN Old = 1 THEN 0 ELSE Sales END) as Old_Sales
FROM    YourTable
GROUP BY
        Country
        ,City

如果您只想查询旧的销售,它就会是这样的。对于新销售,您只需更改WHERE条件。

SELECT  Country
        ,City
        ,SUM(Sales) as Sales 
FROM    YourTable
WHERE   Old = 1
GROUP BY
        Country
        ,City

答案 1 :(得分:1)

回答1:

SELECT  Country
        ,City
        ,SUM(Sales) as Sales 
FROM    YourTable
GROUP BY
        Country
        ,City

ANSWER2:

SELECT  Country
        ,City
        ,SUM(Sales) as Sales 
FROM    YourTable
WHERE   Old = 1
GROUP BY
        Country
        ,City