0

我希望以下代码以多个结束日期运行。这些结束日期必须是该月的第一天。我可以在自己更改结束日期的同时多次执行代码,但这就是我想要从 2001 年到现在的每月数据的大量工作。所以我的猜测是我必须循环这个?

这是我正在使用的代码:

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,但不是相应的日期。这怎么可能?

4

1 回答 1

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

分解您的原始代码:

  1. 返回给定的 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    
    
  2. 从日志中获取状态在一个范围内且 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
    
  3. 从 2 返回计数和状态列

修改后的代码可以:

  1. 识别特定日期内每个 VoerID 的最后一个 LogID

     SELECT VoerID,max(LogID) as MaxLogID 
              from DB.LogStatus
    WHERE Datum >= '2001-01-01'
                        and Datum < '2013-07-01'
    GROUP BY VoerID
    
  2. 通过这些最大 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
    
于 2013-07-09T13:33:29.057 回答