以下是我们的目标:
我们希望为特定用户选择每月和每个月获得的收入。
以下是我们的表格
产品,购买,用户,月份
用户1 .. *产品,产品1 .. *购买
产品的列为“user_id”,购买时有一列'product_id'
months只是一个表格,每个月都包含一个字符串。目前,我们正在使用它来执行一些左连接,如下所示。
SELECT months.name, IFNULL(sum(purchase.price), 0) as revenue
FROM months
LEFT JOIN purchase
ON DATE_FORMAT(purchase.purchase_date, '%M') = months.name
AND DATE_FORMAT(purchase_date, '%Y') = DATE_FORMAT(CURRENT_DATE, '%Y')
AND purchase.status = 2
GROUP BY name
ORDER BY months.id ASC;
这对所有用户和本月所有购买都有效(购买状态为2表示完成)。下一部分是如何根据用户ID过滤这个?表'product'具有我们正在寻找的user_id,表购买具有'product_id'。每当我尝试某些东西时,它既不会做任何事情,也不会删除所有我们不想要的空值。
ATTEMPT @NathanialWools where子句将删除收入为零的所有行(或者因为IFNULL语句而为null)。这就是我试过的:
SELECT name, IFNULL(sum(purchase.price), 0) as revenue
FROM months
LEFT JOIN purchase
ON DATE_FORMAT(purchase.purchase_date, '%M') = months.name
AND DATE_FORMAT(purchase_date, '%Y') = DATE_FORMAT(CURRENT_DATE, '%Y')
AND purchase.status = 2
LEFT JOIN product
ON product.id = purchase.product_id
WHERE product.user_id = 1
GROUP BY name
ORDER BY months.id ASC;
答案 0 :(得分:1)
如果您有可以从中开始的用户列表,请加入到几个月,然后加入产品。 (如果你不只是从产品开始)。
SELECT u.user_id, m.name, IFNULL(sum(p.price), 0) as revenue
FROM user u
CROSS JOIN months m
LEFT JOIN product d
ON u.user_id = d.user_id
LEFT JOIN purchase p
ON DATE_FORMAT(p.purchase_date, '%M') = m.name
AND DATE_FORMAT(p.purchase_date, '%Y') = DATE_FORMAT(CURRENT_DATE, '%Y')
AND p.product_id = d.product_id
AND p.status = 2
WHERE u.user_id = <user you care about>
GROUP BY u.user_id, m.name
ORDER BY m.id ASC;
答案 1 :(得分:0)
LEFT JOIN on product,并添加一个WHERE子句,其中user_id为null或user_id等于您的值。
答案 2 :(得分:0)
你尝试了什么?
SELECT months.name, u.user_id, sum(IFNULL(purchase.price, 0)) as revenue
FROM months
LEFT JOIN purchase pu
ON DATE_FORMAT(purchase.purchase_date, '%M') = months.name
AND DATE_FORMAT(purchase_date, '%Y') = DATE_FORMAT(CURRENT_DATE, '%Y')
AND purchase.status = 2
LEFT JOIN product pr
ON pr.product_id = pr.product_id
LEFT JOIN user u
ON u.user_id = pr.user_id
GROUP BY pu.name, u.user_id
ORDER BY months.id ASC;
答案 3 :(得分:0)
内部选择似乎可以做到这一点。单独购买的左连接不足以过滤。以下是适用于我的解决方案:
SELECT m.name, IFNULL(sum(b.price), 0) as revenue
FROM months as m
LEFT JOIN (SELECT price, purchase_date, status
FROM purchase, product
WHERE purchase.product_id = product.id
AND product.user_id = 1) as b
ON DATE_FORMAT(b.purchase_date, '%M') = m.name
AND DATE_FORMAT(b.purchase_date, '%Y') = DATE_FORMAT(CURRENT_TIMESTAMP, '%Y')
AND status = 2
GROUP BY m.name
ORDER BY m.id ASC
根据您想要查看的用户,显然会更改“1”。
感谢大家的投入,使调试更快。