-1

我有 2 张桌子:

orders
customers

我需要获得“VIP 客户”——即自注册后每月至少订购一次的客户(在 上有一[subscription_date]customers

我想不通:(有什么想法吗?

4

1 回答 1

3

此查询计算每个客户订购的月数,并将其与客户订阅的月数进行比较。
两者具有相同价值的客户是您的 VIP 客户。

SELECT T1.CUSTOMERID AS VIP_CUSTOMERS 
FROM   (SELECT Count(*) AS NUM_MONTHS, 
               CUSTOMERID 
        FROM   (SELECT DISTINCT Month(ORDERDATE), 
                                Year(ORDERDATE), 
                                CUSTOMERID 
                FROM   ORDERS 
                GROUP  BY CUSTOMERID)T 
        GROUP  BY CUSTOMERID)T1 
       INNER JOIN (SELECT CUSTOMERID, 
                          Datediff(MONTHS, SUBSCRIPTION_DATE, Getdate()) AS 
                          NUM_MONTHS 
                   FROM   CUSTOMERS)T2 
               ON T1.CUSTOMERID = T2.CUSTOMERID 
                  AND T1.NUM_MONTHS = T2.NUM_MONTHS 

如果你在SQL Fiddle上设置了一些示例数据,我会尝试根据数据重新编写查询。

于 2012-10-15T13:37:49.800 回答