在使用JOINS一段时间后,我终于设法编写了一个没有语法错误的查询。但是,我需要根据日期限制它输出的数据。
简介是选择客户的ID,然后查看他们已兑换的忠诚度积分总数,并获得他们兑换的最后日期。我的查询可以收集客户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
答案 0 :(得分:1)
这并不难。请看一下我之前回答的这篇文章,了解使用JOIN的一些背景知识。
Selecting multiple columns/fields in MySQL subquery
这是您需要的技巧:一个子查询,用于查找每个客户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