MS-Access:HAVING子句不返回任何记录

时间:2015-11-06 17:16:07

标签: sql ms-access

我有一个Select查询从表中提取客户名称和购买日期。我的目标是仅为在多个不同日期订购的客户选择那些名称和日期。我的代码如下:

SELECT Customer, PurchDate
FROM (SELECT DISTINCT PurchDate, Customer
      FROM (SELECT CDate(FORMAT(DateAdd("h",-7,Mid([purchase-date],1,10)+""+Mid([purchase-date],12,8)), "Short Date")) AS PurchDate,
                 [buyer-name] AS Customer
            FROM RawImport
            WHERE sku ALIKE "%RE%"))
GROUP BY Customer, PurchDate
HAVING COUNT(PurchDate)>1
ORDER BY PurchDate

即使有许多客户拥有多个购买日期,也不会返回任何结果。内部两个选择完美地工作并为每个客户返回一组不同的日期,所以我相信我的GROUP / HAVING / ORDER子句中存在一些问题。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你正在进行内部选择

SELECT DISTINCT PurchDate, Customer

并在outter中选择

GROUP BY Customer, PurchDate

这意味着所有人都

having count(*) = 1

我无法告诉你访问中的确切sintaxis,但你需要这样的东西

我将使用YourTable替代您的内部派生表,以便于阅读

SELECT DISTINCT Customer, PurchDate 
FROM YourTable 
WHERE Customer IN (
                    SELECT Customer
                    FROM (SELECT DISTINCT Customer, PurchDate 
                          FROM YourTable)
                    GROUP BY Customer
                    HAVING COUNT(*) > 1
                  )
  • 内部选择将在一天以上为您提供哪个客户订单。
  • 外部选择将在那些日子为您带来这些客户。

也许你可以尝试一些简单的方法来获取像这样带来超过一天的客户名单

SELECT [buyer-name]
FROM RawImport
WHERE sku ALIKE "%RE%"
GROUP BY [buyer-name]
HAVING Format(MAX(purchase-date,"DD/MM/YYYY")) <> 
       Format(MIN(purchase-date,"DD/MM/YYYY"))