表A
名称     价格     数量
苹果      40         3
苹果      40         6
西瓜      60         3
桃子      50         5
西瓜      50         6
苹果      60         4
苹果      60        1得到的结果表名称    价格    数量
苹果     40       9
西瓜     60       3
桃子     50       5
西瓜     50       6
苹果     60       5判断表A中的名称和价格一致 则合并为一项,并将数量相加。

解决方案 »

  1.   

    USE tempdb
    GO
    IF OBJECT_ID('t') IS NOT NULL DROP TABLE t
    CREATE TABLE t(
    [name] NVARCHAR(20),
    [price] INT,
    [num] INT
    )
    INSERT INTO t
    SELECT '苹果',      40,         3 union all
    SELECT '苹果'      ,40 ,        6 union all
    SELECT '西瓜'      ,60  ,       3 union all
    SELECT '桃子'      ,50  ,       5 union all
    SELECT '西瓜'      ,50  ,       6 union all
    SELECT '苹果'      ,60  ,       4 union all
    SELECT '苹果'      ,60  ,      1SELECT t.name [名称]
    ,t.price [价格]
    ,SUM(num) AS [数量] 
    FROM t GROUP BY t.name,t.price
    /*
    名称 价格 数量
    苹果 40 9
    桃子 50 5
    西瓜 50 6
    苹果 60 5
    西瓜 60 3
    */
      

  2.   

    --测试数据
    if not object_id(N'Tempdb..#A') is null
    drop table #A
    Go
    Create table #A([名称] nvarchar(22),[价格] int,[数量] int)
    Insert #A
    select N'苹果',40,3 union all
    select N'苹果',40,6 union all
    select N'西瓜',60,3 union all
    select N'桃子',50,5 union all
    select N'西瓜',50,6 union all
    select N'苹果',60,4 union all
    select N'苹果',60,1
    Go
    --测试数据结束
    SELECT  名称 ,
            价格 ,
            SUM(数量) AS 数量
    FROM    #A
    GROUP BY 名称 ,
            价格