如何使用多个数据输入中的Stored Procuedure在两个日期之间返回数据

时间:2018-04-03 12:54:44

标签: mysql sql database stored-procedures

我们目前有一个表,每次点击一个字段时都会创建一个新记录(表示RAG状态)。目前,如果点击,则存储的值将反映例如红色;如果他们再次点击它会将视觉效果更改为绿色,但会将新记录写入表格。

e.g。

Field1                 Red                     Time/Date
Field1                 Green                 Time/Date

我们需要考虑如何最好地报告,识别同一个字段可能有多行(不限制人们可以循环的次数),以及"活跃的"价值是。目前只能通过识别最新记录(按时间/日期)来识别,但如果运行数天,这将使报告相当复杂,因为每天可以存在多少记录......

我们已经创建了一个语句(下面)但是希望数据显示在一列而不是一行中:

 select(select Value_Colour from  SOMT_Development.Board_Metrics_Data where Metric_Year = 2018 and Metric_Month = 3 and Metric_Day = 22 and Board_Metrics_ID = 1 order by Date_Created desc limit 1),
       (select Value_Colour from  SOMT_Development.Board_Metrics_Data where Metric_Year = 2018 and Metric_Month = 3 and Metric_Day = 23 and Board_Metrics_ID = 1 order by Date_Created desc limit 1),
       (select Value_Colour from  SOMT_Development.Board_Metrics_Data where Metric_Year = 2018 and Metric_Month = 3 and Metric_Day = 24 and Board_Metrics_ID = 1 order by Date_Created desc limit 1),
       (select Value_Colour from  SOMT_Development.Board_Metrics_Data where Metric_Year = 2018 and Metric_Month = 3 and Metric_Day = 25 and Board_Metrics_ID = 1 order by Date_Created desc limit 1),
       (select Value_Colour from  SOMT_Development.Board_Metrics_Data where Metric_Year = 2018 and Metric_Month = 3 and Metric_Day = 26 and Board_Metrics_ID = 1 order by Date_Created desc limit 1);

我们还需要将它作为两个日期之间的存储过程,以便我们可以轻松更改日期(例如,23/3/2018 - 29/3/2018)。

由于

1 个答案:

答案 0 :(得分:0)

您似乎想要获得给定指标的每日最后一条记录。您可以使用相关子查询来执行此操作:

select bmd.*
from SOMT_Development.Board_Metrics_Data bmd
where bmd.Metric_Year = 2018 and Metric_Month = 3 and
      bmd.Metric_Day in (26, 27, 28) and bmd.Board_Metrics_ID = 1 and
      bmd.Date_Created = (select max(bmd2.Date_Created)
                          from SOMT_Development.Board_Metrics_Data bmd2
                          where bmd2.Board_Metrics_ID = bmd.Board_Metrics_ID and
                                bmd2.Metric_Year = bmd.Metric_Year and
                                bmd2.Metric_Month = bmd.Metric_Month and
                                bmd2.Metric_Day = bmd.Metric_Day
                         );

此子查询可以利用Board_Metrics_Data(Metric_Year, Metric_Month, Metric_Day, Metrics_ID, Date_Created)上的索引。

编辑:

对于任意日期范围:

select bmd.*
from SOMT_Development.Board_Metrics_Data bmd
where bmd.Date_Created >= @start_date and bmd.Date_Created < @end_date and
      bmd.Board_Metrics_ID = 1 and
      bmd.Date_Created = (select max(bmd2.Date_Created)
                          from SOMT_Development.Board_Metrics_Data bmd2
                          where bmd2.Board_Metrics_ID = bmd.Board_Metrics_ID and
                                date(bmd2.Date_Created) = date(bmd.Date_Created)
                         );

此版本的查询有点难以优化。