0

我有这个查询,它给了我不止一个结果。我想对其进行编辑,以便每个 o.Customer_ID 只给我一个结果,然后使用 o.OrderPlaceServerTime 将其设为最接近今天的订单。

这是我的查询:

SELECT
    o.Order_ID,
    o.Customer_ID,
    o.OrderPlaceServerTime,
    o.CustomerOrderTotal
FROM 
    Orders o
    LEFT JOIN Order_LineDetails oln 
    ON oln.Order_ID = o.Order_ID
WHERE 
    o.OrderPlaceServerTime >= '2012-09-01 00:00:00'
AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00'
AND o.CustomerOrderTotal >= '50'
AND oln.Product_ID = '75'

我需要改变什么来实现这一点?

4

2 回答 2

1

我想对其进行编辑,以便每个 o.Customer_ID 只给我一个结果

因此,首先您应该通过按客户 ID 对合格订单进行分组并选择最大值或 OrderPlaceServerTime 来获取合格客户 ID 的最新订单。然后,您可以将这些记录与客户 ID 上的 Orders 和 OrderPlaceServerTime 结合起来,以选择其他两个感兴趣的属性。

SELECT
    o.Order_ID,
    o.Customer_ID,
    o.OrderPlaceServerTime,
    o.CustomerOrderTotal
FROM 
    Orders o
    JOIN (
        SELECT
            o.Customer_ID,
            MAX(o.OrderPlaceServiceTime) 'MaxOrderPlaceServiceTime'
        FROM 
            Orders o
            LEFT JOIN Order_LineDetails oln 
            ON oln.Order_ID = o.Order_ID
        WHERE 
            o.OrderPlaceServerTime >= '2012-09-01 00:00:00'
        AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00'
        AND o.CustomerOrderTotal >= '50'
        AND oln.Product_ID = '75'
        GROUP BY o.Customer_ID
    ) AS A
    ON 
        o.Customer_ID = A.Customer_ID AND 
        o.OrderPlaceServiceTime = A.MaxOrderPlaceServiceTime
于 2012-12-03T15:35:17.193 回答
0

如果我正确理解您的需要,这应该是查询:

    SELECT * FROM 

    ( SELECT
    o.Order_ID,
    o.Customer_ID,
    o.OrderPlaceServerTime,
    o.CustomerOrderTotal
    FROM 
        Orders o
        LEFT JOIN Order_LineDetails oln 
        ON oln.Order_ID = o.Order_ID
    WHERE 
        o.OrderPlaceServerTime >= '2012-09-01 00:00:00'
    AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00'
    AND o.CustomerOrderTotal >= '50'
    AND oln.Product_ID = '75'    
    ORDER BY o.Customer_ID, o.OrderPlaceServerTime DESC ) AS tab1   

    GROUP BY o.Customer_ID;
于 2012-12-03T15:38:00.827 回答