子查询的多个条件(SWITCH或IIF)

时间:2015-06-02 15:45:55

标签: sql ms-access ms-access-2010

如果车辆已经售出,销售取消并重新订购,我会在查询中查找将返回最近销售日期的车辆ID号码(这是通过检查是否有奇数来完成的)与车辆相关的交易)

有时最近的交易日期不是最终销售,而是取消交易(系统以不直观的顺序批量/处理交易)。

注意:我正在使用MS Acces

我需要帮助

编写一个查询以确定最近返回的交易是否为取消交易,然后返回第二个最近的交易。

SQL

SELECT DISTINCT N.vin, 
                N.[trans category], 
                N.[model category], 
                Max(N.[trans date]) 
FROM   new_bbss N 
WHERE  N.[trans category] NOT LIKE '*Individual*' 
       AND ( N.[trans category] ) NOT LIKE '*Corporate*' 
       AND ( n.[trans category] ) NOT LIKE '*Partners*' 
       AND ( n.[trans category] ) NOT LIKE '*Special*' 
       AND ( n.[trans category] ) NOT LIKE '*Employee*' 
       AND ( n.[trans category] ) NOT LIKE '*Mobile*' 
       AND ( n.[trans category] ) NOT LIKE '*JLR FLEET*' 
       AND N.vin IN(SELECT vin 
                    FROM   new_bbss 
                    WHERE  [retailer code] LIKE 'R*' 
                           AND new_bbss.vin NOT IN(SELECT vin 
                                                   FROM   cleansed_vins) 
                    GROUP  BY vin 
                    HAVING Count(vin) > 1 
                           AND Count(vin) MOD 2 = 1) 
GROUP  BY N.vin, 
          N.[trans category], 
          N.[model category] 

数据结构

DataStructure

1 个答案:

答案 0 :(得分:0)

为什么不用子查询消除“取消”事务。请参阅下面代码的第5行。

 SELECT DISTINCT N.vin, 
            N.[trans category], 
            N.[model category], 
            Max(N.[trans date]) 
FROM   (Select * from new_bbss where new_bbss.[trans category] NOT LIKE '*Cancel*')  N 
WHERE  N.[trans category] NOT LIKE '*Individual*' 
   AND ( N.[trans category] ) NOT LIKE '*Corporate*' 
   AND ( n.[trans category] ) NOT LIKE '*Partners*' 
   AND ( n.[trans category] ) NOT LIKE '*Special*' 
   AND ( n.[trans category] ) NOT LIKE '*Employee*' 
   AND ( n.[trans category] ) NOT LIKE '*Mobile*' 
   AND ( n.[trans category] ) NOT LIKE '*JLR FLEET*' 
   AND N.vin IN(SELECT vin 
                FROM   new_bbss 
                WHERE  [retailer code] LIKE 'R*' 
                       AND new_bbss.vin NOT IN(SELECT vin 
                                               FROM   cleansed_vins) 
                GROUP  BY vin 
                HAVING Count(vin) > 1 
                       AND Count(vin) MOD 2 = 1) 
GROUP  BY N.vin, 
      N.[trans category], 
      N.[model category]