查询订单的总金额,其中每个项目的金额大于>

时间:2010-06-23 16:06:09

标签: sql sql-server tsql group-by

在SQL Server 2005上使用以下两个表,如何编写查询以返回订单的First_Name,Last_Name,Order_Date和总金额,其中任何订单(OD_Amount)的任何订单行项目金额都大于100。

订单

Order_ID
First_Name
Last_Name
Order_Date

ORDER_DETAILS

Order_Detail_ID
Order_ID
OD_Item_No
OD_Amount

5 个答案:

答案 0 :(得分:1)

SELECT
    O.first_name,
    O.last_name,
    O.order_date,
    SUM(OD.amount)
FROM
    Orders O
INNER JOIN Order_Details OD ON OD.order_id = O.order_id
WHERE EXISTS
(
    SELECT
    FROM
        Order_Details OD2
    WHERE
        OD2.order_id = O.order_id AND
        OD2.amount > 100
)
GROUP BY
    O.first_name,
    O.last_name,
    O.order_date

答案 1 :(得分:1)

这样的事可能吗?

Select 
  t1.Order_ID, First_Name, Last_Name, Order_Date, Sum(OD_Amount) as Order_Total
From
  Orders t1
Inner Join
  Order_Details t2
    on t1.Order_ID = t2.Order_ID
Where 
  t1.Order_Id in (Select Distinct Order_Id from Order_Details where OD_Amount > 100)
Group By
  t1.Order_ID, First_Name, Last_Name, Order_Date

答案 2 :(得分:0)

这是您希望每个详细订单大于100

的时间
SELECT t1.First_Name, t1.Last_Name, t1.Order_Date, SUM(t2.OD_Amount) AS 'totalAmount'
FROM Orders AS t1
JOIN Order_Details AS t2 ON t1.Order_ID = t2.Order_ID
WHERE t2.OD_Amount > 100
GROUP BY t1.First_Name, t1.Last_Name, t1.Order_Date

如果您希望每个订单本身超过100,那么:

SELECT t1.First_Name, t1.Last_Name, t1.Order_Date, SUM(t2.OD_Amount) AS 'totalAmount'
FROM Orders AS t1
JOIN Order_Details AS t2 ON t1.Order_ID = t2.Order_ID    
GROUP BY t1.First_Name, t1.Last_Name, t1.Order_Date
HAVING SUM(t2.OD_Amount) > 100

答案 3 :(得分:0)

我相信这就是你要找的东西:

SELECT o.First_Name, o.Last_Name, sum(od.OD_Amount) As Order_Total_Amount FROM Order_Details AS od, Orders AS o WHERE o.Order_ID = od.Order_ID AND o.OrderID IN (SELECT Order_ID FROM Order_Details WHERE OD_Amount > 100) GROUP BY o.First_Name, o.Last_Name

答案 4 :(得分:0)

我相信这就是你要找的东西。 EXISTS子句将结果限制为仅包含单个订单项>的订单。 100. GROUP BY通过包含Order_ID列来记录同一天发出的多个订单。

SELECT
  o.First_Name
 ,o.Last_Name
 ,o.Order_Date
 ,SUM(od.OD_Amount) AS Total_Amount
FROM Orders o
  INNER JOIN Order_Details od ON od.Order_ID = o.Order_ID
WHERE EXISTS(SELECT *
             FROM Order_Details od2
             WHERE od2.OD_Amount > 100
               AND od2.Order_ID = o.Order_ID)
GROUP BY
  o.Order_ID
 ,o.First_Name
 ,o.Last_Name
 ,o.Order_Date