我一直在尝试使用SELECT
语句计算表格。我有一张这样的桌子:
--------------------------------------------------------------
AgentID | Date | Incurred | FallOffDate
==============================================================
kegomez | 2012-11-19 | 2.0 | 2013-11-19
kegomez | 2012-11-24 | 0.5 | 2013-11-24
kegomez | 2013-01-21 | 2.0 | 2014-01-21
kegomez | 2013-08-18 | 2.0 | 2014-08-18
我试图在选择期间进行计算,并可能创建一个视图,但到目前为止还没有运气。最后,表格将如下所示。
--------------------------------------------------------------
AgentID | Date | Incurred | 90 | 180 | Total | FallOffDate
==============================================================
kegomez | 2012-11-19 | 2.0 | 2.0 | 2.0 | 2.0 | 2013-11-19
kegomez | 2012-11-24 | 0.5 | 0.5 | 0.5 | 2.5 | 2013-11-24
kegomez | 2013-01-21 | 2.0 | 1.0 | 0.0 | 2.5 | 2014-01-21
kegomez | 2013-08-18 | 2.0 | 2.0 | 2.0 | 4.5 | 2014-08-18
总计列使用前一行的值来计算其值。例如,第 4 行中的日期将需要引用第 3 行中的日期,以查看日期是否更大。我需要用子查询试试这个吗?这最终将如何运作是,如果不再发生,代理将每 90 天到 180 天损失 1 分。因此,我需要引用其他行的原因。如果它有助于此数据当前位于 Excel 中,但变得太大而无法管理,我们需要将其移至性能更好的地方。
SELECT AgentID, Date, Incurred,
@90 := IF(Date<=CURDATE()-90 AND @r=0, Incurred-1.0, IF(Difference>90, Incurred-1, Incurred)) AS 90Day,
@180 := IF(Date<=CURDATE()-90 AND @r=0, Incurred-1.0, IF(Difference>180, Incurred-2, @90)) AS 180Day,
@Total := IF(@180<0,0,IF(FallOffDate<=CURDATE(),0, @180)) AS Total,
FallOffDate
FROM (SELECT mo.AgentID, mo.Incurred, FallOffDate,
@r AS LEAD_date,
DATEDIFF(@r,Date) AS Difference,
(@r := Date) AS Date
FROM (
SELECT m.*
FROM (
SELECT @_date = NULL
) VARIABLE,
attendance m
ORDER BY
AgentID, Date DESC
) mo
WHERE (CASE WHEN @_date IS NULL OR @_date <> date THEN @r := NULL ELSE NULL END IS NULL)
AND (@_date := date) IS NOT NULL) T
ORDER BY AgentID, Date;