Select multiple columns from a table, but group by one

后端 未结 11 1426
逝去的感伤
逝去的感伤 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:34

    You can try the below query. I assume you have a single table for all your data.

    SELECT OD.ProductID, OD.ProductName, CalQ.OrderQuantity
    FROM (SELECT DISTINCT ProductID, ProductName
          FROM OrderDetails) OD
    INNER JOIN (SELECT ProductID, OrderQuantity SUM(OrderQuantity)
                FROM OrderDetails
                GROUP BY ProductID) CalQ
    ON CalQ.ProductID = OD.ProductID
    
    0 讨论(0)
  • 2020-12-12 15:37

    I use this trick for to group by one column when I have a multiple columns selection:

    SELECT MAX(id) AS id,
        Nume,
        MAX(intrare) AS intrare,
        MAX(iesire) AS iesire,
        MAX(intrare-iesire) AS stoc,
        MAX(data) AS data
    FROM Produse
    GROUP BY Nume
    ORDER BY Nume
    

    This works.

    0 讨论(0)
  • 2020-12-12 15:40

    mysql GROUP_CONCAT function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

    SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
    FROM OrderDetails GROUP BY ProductID
    

    This would return:

    ProductID     Names          OrderQuantity
    1001          red            5
    1002          red,black      6
    1003          orange         8
    1004          black,orange   15
    

    Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265

    0 讨论(0)
  • 2020-12-12 15:41
        WITH CTE_SUM AS (
          SELECT ProductID, Sum(OrderQuantity) AS TotalOrderQuantity 
          FROM OrderDetails GROUP BY ProductID
        )
        SELECT DISTINCT OrderDetails.ProductID, OrderDetails.ProductName, OrderDetails.OrderQuantity,CTE_SUM.TotalOrderQuantity 
        FROM 
        OrderDetails INNER JOIN CTE_SUM 
        ON OrderDetails.ProductID = CTE_SUM.ProductID
    

    Please check if this works.

    0 讨论(0)
  • 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 ║
    ╚═══════════╩═════════════╩═══════╝
    
    0 讨论(0)
提交回复
热议问题