我一直在尝试使用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;
答案 0 :(得分:0)
是的,您需要使用子查询执行此操作,尝试使用此类内容(如果您希望第4行访问第3行中的日期):
SELECT mo.AgentID, mo.date,
@r AS 'LAG(date)',
(case when @r<Date then 'YES' when @r is null then 'IS NULL' else 'NO' end) 'Is Bigger',
(@r := Date) AS Date
FROM (
SELECT m.*
FROM (
SELECT @_date = NULL
) variable,
data m
ORDER BY
AgentID
) mo
WHERE (CASE WHEN @_date IS NULL OR @_date <> date THEN @r := NULL ELSE NULL END IS NULL)
AND (@_date := date) IS NOT NULL
您可以看到有效的演示here
或者,如果您希望第3行可以访问第4行中的日期
,则可以尝试此查询SELECT AgentID,date,LEAD_date,concat(Difference,' days') FROM
(SELECT mo.AgentID,
@r AS LEAD_date,
DATEDIFF(@r,Date) as Difference,
(@r := Date) AS Date
FROM (
SELECT m.*
FROM (
SELECT @_date = NULL
) variable,
data 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;
您可以看到有效的演示here