Select multiple columns from a table, but group by one

后端 未结 11 1424
逝去的感伤
逝去的感伤 2020-12-12 14:54

The table name is \"OrderDetails\" and columns are given below:

OrderDetailID || ProductID || ProductName || OrderQuantity

I\'m trying to s

11条回答
  •  轮回少年
    2020-12-12 15:42

    Your Data

    DECLARE @OrderDetails TABLE 
    (ProductID INT,ProductName VARCHAR(10), OrderQuantity INT)
    
    INSERT INTO @OrderDetails VALUES
    (1001,'abc',5),(1002,'abc',23),(2002,'xyz',8),
    (3004,'ytp',15),(4001,'aze',19),(1001,'abc',7)
    

    Query

     Select ProductID, ProductName, Sum(OrderQuantity) AS Total
     from @OrderDetails 
     Group By ProductID, ProductName  ORDER BY ProductID
    

    Result

    ╔═══════════╦═════════════╦═══════╗
    ║ ProductID ║ ProductName ║ Total ║
    ╠═══════════╬═════════════╬═══════╣
    ║      1001 ║ abc         ║    12 ║
    ║      1002 ║ abc         ║    23 ║
    ║      2002 ║ xyz         ║     8 ║
    ║      3004 ║ ytp         ║    15 ║
    ║      4001 ║ aze         ║    19 ║
    ╚═══════════╩═════════════╩═══════╝
    

提交回复
热议问题