按日交易在MySQL排名中添加一列

时间:2016-01-26 22:02:07

标签: mysql

我只是在学习MySQL。我需要按天找出交易等级。在这里,我为我的要求添加了相应的MYSQL查询,该查询目前按天排列所有销售额最高到最低。请帮我添加一个列,该列将交易的排名从最高到最低,并在第二天重置。

这是我当前的工作查询,..

单日标题,价格

SELECT 
    DATE(order_items.created_at) AS the_day, 
    order_items.deal_id, 
    SUM(order_items.item_total) AS daily_total, 
    SUM(order_items.qty) AS units_sold, 
    deals.price,
    deals.title

FROM 
    order_items JOIN deals ON order_items.deal_id = deals.id 

WHERE 
    order_items.created_at >= '2016-01-01 00:00:00' AND order_items.created_at < '2016-01-30 00:00:00' 
    AND 
    order_items.status=1 
    AND 
    order_items.paid=1 

GROUP BY 
    order_items.deal_id 

ORDER BY 
    the_day, 
    daily_total DESC;   

1 个答案:

答案 0 :(得分:0)

最简单的方法是:

  1. 使用现有的SQL - 我想你需要更新你的SQL,确保select中的任何非聚合列也应该在组中
  2. 使用PHP循环(1-5),它可以工作多天
  3. 如果您乐意在一天内获得前5名,则可以在SQL结尾处添加限制5

    如果在一个SQL中需要在多天内每天获得前5个结果,则需要更新SQL以使其更复杂。这里有一个使用行ID的提示见例子:

    select increment counter in mysql

    确定 - 由于您更新了问题以便每天返回前1个结果,因此这更容易:

    第1步:获取每一笔交易的每一天:

    SELECT deal_id, date(created_at) ymd, sum(item_total) daily_total, sum(qty) units_sold
    FROM order_items
    WHERE substr(created_at,1,7) = '2016-01'
    AND status = 1
    AND paid   = 1
    GROUP BY 1,2
    

    第2步:从第1步中找出每天的最佳优惠:

    SELECT aa.ymd, max(aa.daily_total) max_total
    FROM (
        SELECT deal_id, date(created_at) ymd, sum(item_total) daily_total, sum(qty) units_sold
        FROM order_items
        WHERE substr(created_at,1,7) = '2016-01'
        AND status = 1
        AND paid   = 1
        GROUP BY 1,2
    ) as aa
    GROUP BY 1;
    

    请注意,max(item_total)不必与max(unit_sold)相同,所以你需要选择一行,并且不能运行togather

    步骤3:将步骤2加入步骤1并进行处理以找出其余信息:

    SELECT aa.*, deals.price, deal.title
    FROM (
        SELECT aa.ymd, max(aa.daily_total) max_total
        FROM (
            SELECT deal_id, date(created_at) ymd, sum(item_total) daily_total, sum(qty) units_sold
            FROM order_items
            WHERE substr(created_at,1,7) = '2016-01'
            AND status = 1
            AND paid   = 1
            GROUP BY 1,2
        ) as aa
        GROUP BY 1
    ) as bb
    JOIN (
            SELECT deal_id, date(created_at) ymd, sum(item_total) daily_total, sum(qty) units_sold
            FROM order_items
            WHERE substr(created_at,1,7) = '2016-01'
            AND status = 1
            AND paid   = 1
            GROUP BY 1,2
    ) as aa ON bb.ymd = aa.ymd and bb.max_total = aa.daily_total
    JOIN deals ON aa.deal_id = deals.id
    ORDER BY aa.ymd, aa.max_total