复杂的SQL子查询

时间:2012-10-15 13:31:13

标签: sql

我有两张桌子:

orders
customers

我需要获得“VIP客户” - 意味着自注册以来每月至少订购一次的客户([subscription_date]上有一列customers

我无法弄清楚:( 任何想法?

1 个答案:

答案 0 :(得分: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上设置了一些示例数据,我会尝试根据数据重新编写查询。