在数据库比如有这样的记录:
姓名       进货商品      件数    日期
小王       饼干           20     2007-12-3
小王       白菜           10     2007-12-3
小李       牛奶            2     2007-12-3
小李       饼干            5     2007-12-4
小王       饼干            10    2007-12-4根据这两天记录进行查询出来的结果是这样的:姓名     商品       总数
小王     饼干       30
小王     白菜       10
小李     牛奶       2
小李     饼干       5
想问一下大家这个查询应如何写呢,我试的都不行,问一下大家。

解决方案 »

  1.   

    SELECT 姓名, 进货商品 AS 商品, SUM(件数) AS 总数
    FROM TableName
    GROUP BY 姓名, 进货商品
      

  2.   

    select 姓名,进货商品 as 商品,sum(件数) as 总数 form <表名> group by 姓名,进货商品你看这样行不行咯.
      

  3.   

    呵呵,没关系的。唉呀,我还是对sql语句用的不好啊。多谢ideation_shang 和yw1530 ,我试一下。
      

  4.   

    select 姓名,进货商品 as 商品 ,sum(件数) as 总数 
       from TT group by 姓名,进货商品 order by 姓名
      

  5.   

    GROUP BY and ALL
    Transact-SQL provides the ALL keyword in the GROUP BY clause. ALL is meaningful only when the SELECT statement also includes a WHERE clause.If you use ALL, the query results include all groups produced by the GROUP BY clause, even if some of the groups have no rows that meet the search conditions. Without ALL, a SELECT statement that includes GROUP BY does not show groups for which no rows qualify.Here are examples:USE pubs
    SELECT type, AVG(price)
    FROM titles
    WHERE royalty = 10
    GROUP BY typeHere is the result set:type                                    
    ------------ -------------------------- 
    business     17.31                      
    popular_comp 20.00                      
    psychology   14.14                      
    trad_cook    17.97                      (4 row(s) affected)USE pubs
    SELECT type, AVG(price)
    FROM titles
    WHERE royalty = 10
    GROUP BY ALL typeHere is the result set:type                                    
    ------------ -------------------------- 
    business     17.31                      
    mod_cook     (null)                     
    popular_comp 20.00                      
    psychology   14.14                      
    trad_cook    17.97                      
    UNDECIDED    (null)                     (6 row(s) affected)The first query produces groups only for those books that commanded royalties of 10 percent. Because no modern cookbooks have a royalty of 10 percent, there is no group in the results for the mod_cook type.The second query produces groups for all types, including modern cookbooks and UNDECIDED, even though the modern cookbook group does not include any rows that meet the qualification specified in the WHERE clause.The column that holds the aggregate value (the average price) is NULL for groups that lack qualifying rows.