2

我想知道orderid使用GROUP BY语句对每个结果进行分组的最佳方法。

当前查询:

SELECT T.orderid,
       Inventory.partid,
       Inventory.Description,
       OrderItems.Qty,
       '$' + STR(Inventory.price,8,2) AS UnitPrice,
       '$' + STR(OriginalCost,8,2) AS OriginalCost,
       '$' + STR(QuantityDiscount,8,2) AS QuantityDiscount, 
       '$' + STR((OriginalCost  - QuantityDiscount),8,2) AS FinalCost
  FROM (
       SELECT Orders.Orderid, Inventory.partid, Description, Qty, 
              Inventory.price AS UnitPrice, 
              (OrderItems.Qty * Inventory.price) AS OriginalCost, 
              CASE WHEN OrderItems.Qty >= 5
                     THEN ((OrderItems.Qty * Inventory.price) * .05)
                   WHEN OrderItems.Qty >= 10
                     THEN ((OrderItems.Qty * Inventory.price) * .10)
                   ELSE 0
              END AS QuantityDiscount
         FROM Orders,OrderItems,Inventory
       ) AS T
  JOIN OrderItems ON OrderItems.orderid = OrderItems.orderid
  JOIN Inventory ON ORDERITEMS.partid = Inventory.partid
ORDER BY T.QTY DESC

DB图:

在此处输入图像描述

示例结果 这是我从当前代码中得到的部分结果。我希望所有具有相同 id 的订单都应该组合在一起。

orderid partid Description Qty  UnitPrice OriginalCost QuantityDiscount FinalCost
------- ------ ----------- ---- --------- ------------ ---------------- ---------
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
6148    1006   gizmo       1    $   11.35 $  113.50    $    5.67        $  107.83
4

2 回答 2

1

A simplyfied example if you want to still get the part informations:

  SELECT orderid,
         partid,
         sum(Qty)
    FROM yourTable
GROUP BY oderid, partid

So, this groups the table by oderid and partid and returns the sum of Qty for each group. For more details on how to use group by, give Google a chance. Here is one tutorial I found instantly.

于 2013-04-13T19:46:28.047 回答
0

您也可以使用带有 DISTINCT 关键字的SELECT语句而不是 GROUP BY 子句

SELECT DISTINCT
       Col1,
       Col2,
       ...
FROM ...
于 2013-04-14T11:32:14.570 回答