从表T1中获得3位访问量最大的客户,并从表T2中获得前5名产品

时间:2014-06-22 22:23:58

标签: sql db2

我需要从表T1中获取3位访问量最大的客户,然后从表T2中获取他们购买的前5种产品。

表T1有     KIRK访问了3次,Hulk访问了3次,John访问了2次..所以这三个应该只能获取。 Thor和Rndm的家伙曾经访问过一次所以他们离开了,只有前三名才被拿走

Table 1 (T1)
-----------------------------------
NAME       AGE   VISITOR CODE
-----------------------------------
KIRK     18    1285
THOR     99    1284
KIRK     18    1285
HULK     19    1286
KIRK     18    1285
JOHN     19    0007   
HULK     19    1286
JOHN     19    0007
HULK     19    1286
RNDM     19    0008


 Table 2 (T2)
-----------------------------------
PRODUCT  MRP   VISITOR CODE    --EXAMPLE ONLY FOR KIRK TOP 3 PRODS ARE A then D then C.
-----------------------------------
A        111    1285
A        111    1285
A        111    1285
B        191    1285
C        192    1285
C        192    1285
D        190    1285
D        190    1285
D        190    1285
D        190    1285

我做的是:

SELECT                              
       T2.PRODUCT ,                  
       COUNT(*) AS X                  
  FROM T1,T2
 WHERE T2.VISITOR CODE =
      (SELECT                              
              T1.VISITOR CODE ,                  
              COUNT(*) AS X                  
       FROM  T1,T2
       GROUP BY T1.VISITOR CODE 
       ORDER BY X DESC        
       FETCH FIRST 3 ROWS ONLY)
 GROUP BY T1.VISITOR CODE 
 ORDER BY X DESC

问题是:我只需要来自子查询的T1.VISITOR CODE来匹配T2表的T2.VISITOR CODE。 但是我也在T1表子查询中使用了count。

输出结果:

NAME     PRODUCT     VISITOR CODE 
KIRK     A           1285
KIRK     D           1285
KIRK     C           1285
HULK     C           1286
HULK     A           1286
HULK     B           1286 -- AND THEN  JOHN AND HIS 3 PRODUCTS

1 个答案:

答案 0 :(得分:1)

您可以使用派生表来解决此查询。第一个派生表包含前3个访问者,它连接到第2个派生表,其中包含每个访问者的前5个产品。

SELECT t1.*, t2.*
FROM
    (SELECT
        NAME,
        AGE,
        VISITOR_CODE,
        COUNT(*) VISIT_COUNT
    FROM
        TABLE1t t1
    GROUP BY VISITOR_CODE
    ORDER BY VISIT_COUNT DESC LIMIT 3) t1
JOIN (
    SELECT 
        PRODUCT,
        MRP,
        VISITOR_CODE,
        RANK() OVER 
        (PARTITION BY t3.VISITOR_CODE ORDER BY t3.product_count DESC) AS rank
    FROM (
        SELECT
            PRODUCT,
            MRP,
            VISITOR_CODE,
            COUNT(*) product_count
        FROM TABLE2
        GROUP BY
            PRODUCT,
            MRP,
            VISITOR_CODE
    ) t3 WHERE rank <= 5
) t2 ON t1.VISITOR_CODE = t2.VISITOR_CODE