我希望以下代码与多个结束日期一起运行。这些结束日期必须是该月的第一天。 我可以在更改结束日期的同时多次执行代码,但这对于我需要从2001年到现在的montly数据的大量工作。所以我的猜测是我必须循环这个?
以下是我正在使用的代码:
Select t4.Count, t4.Status
From(
SELECT count(l.VoerID) as Count, l.Datum, l.Status, l.LogID
FROM (
SELECT k.VoerID, k.Datum, MAX(k.LogID) AS LogID
FROM DB.LogStatus k
Where Datum > '2001-01-01'
and Datum < '2013-07-01'
GROUP BY k.VoerID
) m
JOIN DB.LogStatus l
ON l.VoerID = m.VoertuigID AND l.LogID = m.LogID
Where status in ('x',y,'z')
Group by Status
)t4
谁可以提供帮助?
编辑::::: @STEPH
当我使用这段代码的和平时(1):
SELECT VoertID,max(LogID) as MaxLogID,Datum
from DB.LogStatus
WHERE Datum >= '2001-01-01'
and Datum < '2013-07-01'
and VoerID = '50789'
GROUP BY VoerID
我使用最后一个LogID但不是相应的日期获得VoerID 50789。怎么可能?
答案 0 :(得分:0)
根据您的输出,您需要操纵您的日期以始终返回本月的第一天。
在下面的SQL中,我提出了一个这样做的方法,它涉及计算在本月初(相对于每个日期)已经过去多少天并且减去它。
SELECT date_sub(Datum,interval day(Datum)-1 day) datum, status, count(l.VoerID) as count
FROM DB.LogStatus l
INNER JOIN (SELECT VoerID,max(LogID) as MaxLogID
from DB.LogStatus
WHERE Datum >= '2001-01-01'
and Datum < '2013-07-01'
GROUP BY VoerID) maxl on l.VoerID=Maxl.VoerID and l.LogID=Maxl.MaxLogID
Where status in ('x','y','z')
and Datum >= '2001-01-01'
and Datum < '2013-07-01'
GROUP BY date_sub(Datum,interval day(Datum)-1 day),status
分解原始代码:
返回给定的VoerID,返回FIRST Date和MAX LogID
SELECT k.VoerID, k.Datum, MAX(k.LogID) AS LogID
FROM DB.LogStatus k
Where Datum > '2001-01-01'
and Datum < '2013-07-01'
GROUP BY k.VoerID
从日志中获取状态在一定范围内且LogID匹配的所有项目,表格中的VoerID与派生表中的VoertuigID匹配(实际上不存在于代码中)。按日志状态分组并获取FIRST Datum,FIRST LogID和COUNT
SELECT count(l.VoerID) as Count, l.Datum, l.Status, l.LogID
FROM ( step1 ) m
JOIN DB.LogStatus l
ON l.VoerID = m.VoertuigID AND l.LogID = m.LogID
Where status in ('x',y,'z')
Group by Status
从2
修订后的代码确实:
标识特定日期内每个VoerID的最后一个LogID
SELECT VoerID,max(LogID) as MaxLogID
from DB.LogStatus
WHERE Datum >= '2001-01-01'
and Datum < '2013-07-01'
GROUP BY VoerID
通过这些最大LogID限制日志,然后过滤相关状态,然后计算每个月的每个状态的行数
SELECT date_sub(Datum,interval day(Datum)-1 day) datum, status, count(l.VoerID) as count
FROM DB.LogStatus l
INNER JOIN ( m ) maxl on l.VoerID=Maxl.VoerID and l.LogID=Maxl.MaxLogID
Where status in ('x','y','z')
and Datum >= '2001-01-01'
and Datum < '2013-07-01'
GROUP BY date_sub(Datum,interval day(Datum)-1 day),status