0

在使用 JOINS 一段时间后,我终于设法编写了一个没有语法错误的查询。但是,我需要根据日期限制它输出的数据。

简而言之,选择客户的 ID,然后查看他们兑换的忠诚度积分总数,并获取他们兑换的 LAST DATE。我的查询可以收集客户 ID、忠诚度会员 ID 和积分数,但是,我得到了他们兑换的每个日期,而不仅仅是最后一个。

有没有办法让查询只给出给定客户 ID 的最后日期?

我的查询是:

SELECT  gv.amount AS gv_amount, 
        gv.customer_id AS gv_customer_id, 
        h.date AS h_date, 
        c.loyalty_id AS c_loyalty_id
FROM coupon_gv_customer gv
   INNER JOIN loyalty_codes_redeem_history h 
        ON gv.customer_id = h.customer_id
    INNER JOIN customers c 
        ON gv.customer_id = c.customers_id 

h_date 的格式为 YYYY-MM-DD HH:MM:SS

4

1 回答 1

0

这并不难。请查看我不久前回答的这篇文章,了解有关使用 JOIN 的一些背景信息。

在 MySQL 子查询中选择多个列/字段

这是您需要的技巧:查找每个客户 ID 的最新日期的子查询。这是:

 SELECT customer_id, MAX(date) as date
   FROM loyalty_codes_redeem_history
  GROUP BY customer_id

然后你需要把这个子查询——这个虚拟表——加入到你的整体查询中。我认为结果将如下所示:

     SELECT gv.amount                 AS gv_amount, 
            gv.customer_id            AS gv_customer_id, 
            customer_latest_date.date AS h_date, 
            c.loyalty_id              AS c_loyalty_id
       FROM coupon_gv_customer gv
 INNER JOIN loyalty_codes_redeem_history h 
               ON gv.customer_id = h.customer_id
 INNER JOIN customers c 
               ON gv.customer_id = c.customers_id 
 INNER JOIN (
                 SELECT customer_id, 
                        MAX(date) AS date
                   FROM loyalty_codes_redeem_history
               GROUP BY customer_id
            ) customer_latest_date
               ON customer_latest_date.customer_id = c.customers_id

你明白它是如何工作的吗?子查询在 INNER JOIN 中使用,就好像它是一个表,实际上它是:一个虚拟表。

编辑

要汇总您的 coupon_gv_customer 表中的忠诚度积分,您需要另一个汇总查询,如下所示:

 SELECT customer_id,
        SUM(amount) AS amount
   FROM coupon_gv_customer
  GROUP BY customer_id

然后,我认为您的查询将是这样的。它会给每个客户一排,我认为这是你想要得到的。没有任何兑换或日期的客户将不会出现。

      SELECT  c.customers_id,
              c.loyalty_id,
              customer_latest_date.date
              customer_points.amount
        FROM  customers c
  INNER JOIN  (
                    SELECT customer_id,
                           SUM(amount) AS amount
                      FROM coupon_gv_customer
                  GROUP BY customer_id
              ) customer_points ON c.customers_id = customers_points.customer_id
  INNER JOIN  (
                    SELECT customer_id, 
                           MAX(date) AS date
                      FROM loyalty_codes_redeem_history
                  GROUP BY customer_id
            ) customer_latest_date ON customer_latest_date.customer_id = c.customers_id
于 2013-03-18T14:06:02.257 回答