我不是MYSQL查询的最佳选择,但是这个问题让我难以理解,我的基本样本MYSQL数据是:
INSERT INTO `spending` (`spend_id`, `spend_user_id`, `spend_sender_id`, `spend_offer_id`, `spend_amount`, `spend_click`, `spend_date`) VALUES
(2, 190, 190, 34591, '0.15', 1, '2018-05-14 22:39:47'),
(3, 190, 190, 34591, '0.15', 1, '2018-05-14 22:39:52'),
(4, 190, 7, 34591, '0.15', 1, '2018-05-14 22:40:07'),
(5, 190, 10, 34591, '0.15', 1, '2018-05-14 22:42:15'),
(6, 190, 7, 34591, '0.15', 1, '2018-05-15 06:55:56'),
(7, 190, 7, 34591, '0.15', 1, '2018-05-16 17:05:29'),
(8, 190, 7, 34591, '0.15', 1, '2018-05-16 17:05:32');
我的目标是将数据细分为2个主要部分点击次数和费用,基本上每个条目都被视为1次点击,html信息中心如下:
然后是4个子部分。
4个子部分是{strong>今天,昨天,上周,上个月的点击和费用spend_user_id
我不知道最好的方法,任何指导都是理解!
答案 0 :(得分:2)
您需要为显示的每一列(今天,昨天,周,月)单独显示子查询。
例如,要获取月初至今的结果,请使用此子查询。
SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH
拥有所有这些子查询后,您可以将它们连接在一起以获得结果。 (注意:每个子查询只产生一行,因此不加入它们
ON
条件也产生一行。)
像这样的东西。 (http://sqlfiddle.com/#!9/f8e090/7/0)
SELECT today.clicks, today.spend_amount,
yesterday.clicks, yesterday.spend_amount,
week.clicks, week.spend_amount,
month.clicks, month.spend_amount
FROM
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE()) today
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 1 DAY
AND spend_date < CURDATE()) yesterday
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= CURDATE() - INTERVAL 7 DAY
AND spend_date < CURDATE()) week
JOIN
(SELECT COUNT(*) clicks, SUM(spend_amount) spend_amount
FROM spending
WHERE spend_date >= LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH) month
我猜到你的意思,确切地说是今天,昨天,周和月。在报告具有商业意义之前,您需要弄明白这一点。