按商店(数量),列出客户访问商店的最大次数

时间:2018-11-30 00:51:13

标签: sql teradata store

我要链接的三个表是item_scan_fact,member_dimension和store_dimension。到目前为止,这就是我所拥有的:

SELECT 
    store_dimension.store_number, 
    member_dimension.member_number  
    COUNT (item_scan_fact.visit_number) AS NumVisits 
FROM 
    member_dimension, 
    item_scan_fact 
    INNER JOIN store_dimension
        ON item_scan_fact.member_key = member_dimension.member_key
       AND item_scan_fact.store_key = store_dimension.store_key 
GROUP BY 
    store_dimension.store_number, 
    member_dimension.member_number, NumVisits;

3 个答案:

答案 0 :(得分:0)

在表面上似乎可以用Common Table Expressions来解决

此帮助是否将您指向正确的方向?

WITH s1 -- JJAUSSI: Find the visit_number_count by member_key and store_key
AS
(SELECT isf.member_key
       ,isf.store_key
       -- JJAUSSI: DISTINCT resolves a potential 1:N (one to many) relationship here
       ,COUNT( DISTINCT isf.visit_number) AS visit_number_count 
   FROM item_scan_fact isf
  GROUP BY isf.member_key
          ,isf.store_key),
s2 -- JJAUSSI: Find the visit_number_count_max by member_key
AS
(SELECT s1.member_key
       ,MAX(s1.visit_number_count) AS visit_number_count_max
  FROM s1
 GROUP BY s1.member_key)
-- JJAUSSI: Use this version to see the list of store_key values 
-- that have the visit_number_count_max value. This has the potential
-- to be a 1:N relationship.
SELECT s1.member_key
      ,md.member_number 
      ,s1.store_key
      ,sd.store_number
      ,s1.visit_number_count
  FROM s2 INNER JOIN s1
             ON s2.member_key = s1.member_key
            AND s2.visit_number_count_max = s1.visit_number_count
          INNER JOIN store_dimension sd
             ON sd.store_key = s1.store_key
          INNER JOIN member_dimension md
             ON md.member_key = s1.member_key;

如果这是您要去的...恭喜!继续下一个查询!

如果最终您是对每个member_key发出单个 store_key响应(基本上是要确定member_key的“主要” store_key),则可能需要采取其他步骤(取决于您的数据)。

以下是一些想法:

  1. 基于的其他一些可加方面来评估member_key item_scan_fact(例如已支付的总价?)
  2. 如果您考虑给定member_key的所有具有相同价值的store_key值具有相同的visit_number_count_max值,则只需选择MAX或MIN的store_key即可。

答案 1 :(得分:0)

您似乎想要:

SELECT member_number, MAX(NumVisits)
FROM (SELECT sd.store_number, md.member_number  
             COUNT(*) AS NumVisits 
      FROM member_dimension md JOIN
           item_scan_fact isf
           ON md.member_key = isf.member_key JOIN
           store_dimension sd
           ON isf.store_key = sd. store_key 
      GROUP BY sd.store_number, md.member_number
     ) sm
GROUP BY member_number;

答案 2 :(得分:0)

如果要同时返回最大数量和匹配的客户编号,则可以应用Teradata SQL扩展名qualify

SELECT sd.store_number, md.member_number  
       COUNT(*) AS NumVisits 
FROM member_dimension md JOIN
     item_scan_fact isf
     ON md.member_key = isf.member_key JOIN
     store_dimension sd
     ON isf.store_key = sd. store_key 
GROUP BY sd.store_number, md.member_number
QUALIFY
   rank() -- might return multiple rows with the same max, ROW_NUMBER a single row
   over (partition by sd.store_number 
        order by NumVisits desc) = 1