SQL嵌套语句与产品数量的问题

时间:2018-05-08 13:27:52

标签: mysql

我正在学习SQL嵌套语句,但我遇到了一个问题。我想做的是使用上个月的图书ID获取图书的总销售额,并将其与本月的销售额进行比较。所有购买都记录在book_download_log表中,表格具有以下结构

Timestamp    Book ID   Price    
May 1st      10        100
May 2nd      20        200
May 3rd      30        300

这是我当前的查询

SELECT b.book_id, CONCAT(FORMAT(((this_month/last_month)*100)-100,2),'%') AS Diff, this_month, last_month
FROM 
book_download_log b
JOIN
    (SELECT count(*) AS last_month FROM
        book_download_log b
            WHERE b.book_price > 0 AND
            date(b.timestamp) BETWEEN '2018-04-01' AND '2018-04-08') t1
 JOIN
    (SELECT count(*) AS this_month FROM
        book_download_log b
            WHERE b.book_price > 0 AND
            date(b.timestamp) BETWEEN '2018-05-01' AND '2018-05-08') t2
GROUP BY b.book_id
ORDER BY Diff Desc

我成功的做法是提取在此期间购买的所有图书的总数,而不是单个图书购买的数量。这就是我现在的结果

Book ID    Diff     This Month     Last Month
1          17.6%    652            577
69         17.6%    652            577
102        17.6%    652            577

我需要编辑哪些内容来显示两个时期的个人图书销售额?

2 个答案:

答案 0 :(得分:1)

你可以选择:

SELECT
b.book_id as id,
SUM(IF(MONTH(b.timestamp) = MONTH(CURDATE()), b.book_price, 0)) as thisMonth,
SUM(IF(MONTH(b.timestamp) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)), b.book_price, 0)) as lastMonth,
CONCAT(SUM(IF(MONTH(b.timestamp) = MONTH(CURDATE()), b.book_price, 0)) - SUM(IF(MONTH(b.timestamp) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)), b.book_price, 0)), '%') as diff
FROM book_download_log b
WHERE DATE_FORMAT(b.timestamp, '%Y-%m-%d') BETWEEN DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 MONTH), '%Y-%m-01') AND DATE_FORMAT(CURDATE(), '%Y-%m-31')
GROUP BY b.book_id

这也适用于多年(例如,您在1月份,而上个月则在另一年)并且如果您在数据库中的当前日期之后有数据(例如,您在1月份,并且您有数据存储在同一年2月的数据库中,它可以发生)

请参阅SQL小提琴来测试它: http://sqlfiddle.com/#!9/4ec6c8/7

答案 1 :(得分:0)

首先,您希望按月对购买进行分组。我选择了SELECT EXTRACT(MONTH FROM" 2017-06-15")。然后使用SUM()获得每个月的所有购买,而不是COUNT()。所以你应该有这样的东西:

Select EXTRACT(MONTH FROM "2017-06-15") as Month, Book_id, sum(price) from 
book_download_log group by Book_id, Month

然后提取上个月和当月。

    SELECT b.book_id, CONCAT(FORMAT(((this_month/last_month)*100)-100,2),'%') 
    AS Diff
    FROM 
    (Select EXTRACT(MONTH FROM "2017-06-15") as Month, Book_id, sum(price) from 
     book_download_log group by Book_id, Month)
    join
   Select EXTRACT(MONTH FROM "2017-04-15") as Last_Month, Book_id, sum(price) from 
     book_download_log download group by Book_id, Last_Month
    on download.Book_id = book_download_log.Book_id