SQL加入Order by和Group by

时间:2014-07-10 07:32:14

标签: sql excel-vba ms-access-2007 vba excel

您好我正在尝试从另一个Excelworkbook中加入Excel。

第一个表中的主键是Part_No。这不是主键,因此无法进行1对1连接。

我想从匹配LIKE和NOT LIKE关键字的结果中选择最佳订单状态。

WHERE语句工作正常但是FIRST语句似乎与ORDER BY不匹配,结果是一些随机的。有时我会在库存中有相同零件的订单时获得“已取消零件”。当只使用In Stock first执行内部Select时,我看到两行。

我在Excel vba中使用Provider=Microsoft.ACE.OLEDB.12.0进行ADODB连接。

有什么问题?谢谢你的帮助!

SELECT 
    FIRST(o.Part_No), 
    FIRST(o.Order_Desc),
    FIRST(o.Order_Status)
FROM 
    Parts 
LEFT JOIN
    (
        SELECT * 
        FROM Orders
        WHERE 
            Orders.Order_Desc Like '%keyword%' AND 
            Orders.Order_Desc Not Like '%otherkeyword%'
        ORDER BY 
            IIF(Orders.Order_Status = 'In Stock' , 1, 
            IIF(Orders.Order_Status = 'In Transit' , 2, 
            IIF(Orders.Order_Status = 'Ordered' , 3, 
            IIF(Orders.Order_Status = 'Canceled' , 4)))) ASC
    ) AS o
    ON Parts.Part_No = o.Part_No
GROUP BY Parts.Part_No;

这是一个例子。

List Parts
Part No
1
2

List Orders
Part No    Order_Desc         Order_Status
1          keyword            In Stock
1          keyword            Canceled
2          keyword            Ordered
2          not keyword        In Stock
2          keyword            Canceled
3          keyword            Ordered
3          keyword            In Stock
3          keyword            In Stock
5          not keyword        In Stock

What i get
1          keyword            Canceled (seems Random right or wrong)
2          keyword            Ordered

Desired Result
1          keyword            In Stock
2          keyword            Ordered

希望这个例子有帮助! 我在这里发布了一些新帖子。对不起奇怪的桌子

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
COUNT(o.Part_No), 
FIRST(o.Part_No), 
FIRST(o.Order_Status), 
FIRST(o.Order_No), 
FIRST(o.Order_Desc),
        IIF(Orders.Order_Status = 'In Stock' , 1, 
        IIF(Orders.Order_Status = 'In Transit' , 2, 
        IIF(Orders.Order_Status = 'Ordered' , 3, 
        4))) AS Order_Status_OrderBy

FROM 
Parts 
LEFT JOIN
(
    SELECT * 
    FROM Orders
    WHERE 
        Orders.Order_Desc Like '%keyword%' AND 
        Orders.Order_Desc Not Like '%otherkeyword%'
    ORDER BY 
        Order_Status_OrderBy
) AS o
ON Parts.Part_No = o.Part_No
GROUP BY Parts.Part_No;