MySQL - 按日期排序的查询无法获取最新记录

时间:2015-12-23 09:25:49

标签: mysql sql

我的数据库设置如下:

http://sqlfiddle.com/#!9/2c5fc

我要做的是获取每个商店的清单,以及他们的上一个预算金额(每个时间表在预算中的总额*他们对该时间表的分配/ 100)。

某些商店可能没有为上一个预算设置分配,因此我需要设置分配的最后一个预算,如果没有设置分配或没有预算,则需要NULL。

我有以下SQL查询:

SELECT s.StoreID,s.CentreID, budgetcalc.amount, budgetcalc.BudgetDate FROM store as s
LEFT JOIN centre on s.CentreID = centre.CentreID
LEFT JOIN (SELECT BudgetDate, SUM(sch.Amount*appt.Percentage/100) as amount, appt.StoreID from budget b
    INNER JOIN schedule as sch on b.BudgetID = sch.BudgetID
    INNER JOIN apportionment as appt on sch.ScheduleID = appt.ScheduleID 
    GROUP BY appt.StoreID, b.BudgetID
    ORDER BY STR_TO_DATE(b.BudgetDate,'%d-%m-%y') DESC
) as budgetcalc on s.StoreID = budgetcalc.StoreID
GROUP BY s.StoreID
ORDER BY s.StoreID, STR_TO_DATE(budgetcalc.BudgetDate,'%d-%m-%y') DESC;

然而,这有一个问题就是不返回去年,它将会随机返回前一年,无论我返回子查询的顺序如何。

2 个答案:

答案 0 :(得分:1)

很难从表格声明中解决问题,但您需要获取每个商店的最新预算日期,然后将其与您的子查询相关联,以获取每个商店/预算的预算详细信息。

未经测试但是这样的事情: -

SELECT s.StoreID,
        s.CentreID, 
        budgetcalc.amount, 
        budgetcalc.BudgetDate 
FROM store as s
LEFT OUTER JOIN centre ON s.CentreID = centre.CentreID
LEFT OUTER JOIN
(
    SELECT appt.StoreID, 
            MAX(BudgetDate) AS latestBudgetDate
    FROM budget b
    INNER JOIN schedule as sch ON b.BudgetID = sch.BudgetID
    INNER JOIN apportionment as appt ON sch.ScheduleID = appt.ScheduleID 
    GROUP BY appt.StoreID
) latest_budget
ON s.StoreID = latest_budget.StoreID 
LEFT OUTER JOIN 
(
    SELECT BudgetDate, 
            appt.StoreID, 
            SUM(sch.Amount*appt.Percentage/100) as amount 
    FROM budget b
    INNER JOIN schedule as sch ON b.BudgetID = sch.BudgetID
    INNER JOIN apportionment as appt ON sch.ScheduleID = appt.ScheduleID 
    GROUP BY appt.StoreID, b.BudgetID
) as budgetcalc 
ON latest_budget.StoreID = budgetcalc.StoreID
AND latest_budget.latestBudgetDate = budgetcalc.BudgetDate
ORDER BY s.StoreID, 
        budgetcalc.BudgetDate DESC;

答案 1 :(得分:0)

在Kickstart的帮助下,这是有效的答案:

SELECT s.StoreID,s.CentreID, SUM(sch.Amount*appt.Percentage/100) as amount, b.BudgetDate FROM store as s
INNER JOIN centre on s.CentreID = centre.CentreID
LEFT JOIN budget as b on b.BudgetID = 
    (
        SELECT budget.BudgetID from budget 
        INNER JOIN schedule on budget.BudgetID = schedule.BudgetID 
        INNER JOIN apportionment on schedule.ScheduleID = apportionment.ScheduleID
        where CentreID = s.CentreID AND apportionment.StoreID = s.StoreID
        ORDER BY BudgetDate DESC limit 1
    )
LEFT JOIN schedule as sch on b.BudgetID = sch.BudgetID
LEFT JOIN apportionment as appt on sch.ScheduleID = appt.ScheduleID AND appt.StoreID = s.StoreID
GROUP BY s.StoreID
ORDER BY s.StoreID ASC;