简体   繁体   English

如何根据最新的 Date 和 Time OR Date_Time 列查询 SQL 的最新记录?

[英]How do I query SQL for the latest record based on latest Date and Time OR Date_Time columns?

Situation: SerialNumber has duplicate rows and I need to select the latest records and get what is the Status value (either it PASS or FAIL does not matter).情况: SerialNumber 有重复行,我需要 select 最新记录并获取 Status 值是什么(PASS 或 FAIL 都没有关系)。

SerialNumber must be check based on the previous StationNumber.必须根据之前的 StationNumber 检查 SerialNumber。 Example: I want to get the Status value of the latest record SerialNumber 197601234512345 in Station 2, so value StationNumber = @Station in the command line below is actually "Station 1"示例:我想获取Station 2中最新记录SerialNumber 197601234512345的Status值,所以下面命令行中的value StationNumber = @Station其实就是“Station 1”

Scenario: SerialNumber can either be pass or fail in Station 1, then SerialNumber exp:197601234512345 is brought forward to Station 2. In Station 2, need to check what latest Status of that SerialNumber exp:197601234512345 has in the previous StationNumber (Station 1).场景: SerialNumber 在Station 1 中可以通过或失败,然后将SerialNumber exp:197601234512345 提前到Station 2。在Station 2 中,需要检查该SerialNumber exp:197601234512345 在上一个StationNumber(Station 1)中的最新状态.

Example table in the database db:数据库 db 中的示例表:

ID ID SerialNumber序列号 Date日期 Time时间 Date_Time约会时间 Status地位 StationNumber电台编号
213939 213939 197601234512344 197601234512344 2021-04-28 2021-04-28 11.53 AM上午 11.53 2021-04-28 11:53:00 2021-04-28 11:53:00 PASS经过 Station 1 1号站
213940 213940 197601234512345 197601234512345 2021-04-28 2021-04-28 11.54 AM上午 11.54 2021-04-28 11:54:00 2021-04-28 11:54:00 FAIL失败 Station 1 1号站
213941 213941 197601234512345 197601234512345 2021-04-28 2021-04-28 12.11 PM中午 12 点 11 分 2021-04-28 14:30:00 2021-04-28 14:30:00 FAIL失败 Station 2 2号站
213942 213942 197601234512345 197601234512345 2021-04-28 2021-04-28 12.11 PM中午 12 点 11 分 2021-04-28 14:31:00 2021-04-28 14:31:00 FAIL失败 Station 2 2号站
213943 213943 197601234512344 197601234512344 2021-04-28 2021-04-28 12.00 PM中午 12 点 2021-04-28 14:35:00 2021-04-28 14:35:00 FAIL失败 Station 3 3号站
213944 213944 197601234512344 197601234512344 2021-04-28 2021-04-28 12.05 PM下午 12.05 2021-04-28 14:46:00 2021-04-28 14:46:00 FAIL失败 Station 3 3号站
213945 213945 197601234512344 197601234512344 2021-04-28 2021-04-28 12.10 PM中午 12 点 10 分 2021-04-28 14:47:00 2021-04-28 14:47:00 PASS经过 Station 3 3号站

Note: All datatype for the columns are VARCHAR(45)注意:列的所有数据类型都是VARCHAR(45)

So far, the SQL commands that I have tried has NO Error, but the MySqlreader does NOT Execute the ExecuteReader() which hold the SQL command.到目前为止,我尝试过的 SQL 命令没有错误,但是 MySqlreader 不执行包含 SQL 命令的 ExecuteReader()。 How do I know it?我怎么知道? By doing the test display label on Label13.Text in Update 1: C# code, At the front-end system it display till Label13.Text = "Check 3";通过在更新 1 中的 Label13.Text 上进行测试显示 label:C# 代码,在前端系统显示直到 Label13.Text = "Check 3"; then direct gives me Label13.Text = "Bad Output";然后直接给我 Label13.Text = "Bad Output";

Below here are my five tried sql commands.下面是我尝试的五个 sql 命令。 But none of it works hurm =(:但是这些都不起作用 =(:

Select Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))
or
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime)) Group By Status
or
Select Top Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))
or
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station Oder By Status desc limit 1
or
Select a.Status from db.station INNER JOIN (Select SerialNumber, Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))group by SerialNumber) b on a.Status = b.Status

Update 1: C# code on 2021-04-29更新 1:C# 代码于 2021-04-29

if (textbox1.Text != "")
                    {
                        con.Open();
                        Label13.Text = "Check 1";

                        //new command
                        MySqlCommand cmdd = new MySqlCommand("Select SerialNumber, Status from db.station where SerialNumber = @SN  and StationNumber = @Station order by CAST(Date_Time as DateTime) desc limit 1 ", con);
                        
                        Label13.Text = "Check 2";
                        cmdd.Parameters.AddWithValue("@SN", textbox1.Text);
                        cmdd.Parameters.AddWithValue("@Station", "Station 1");
                        
                        Label13.Text = "Check 3";
                        MySqlDataReader read = cmdd.ExecuteReader();
                        Label13.Text = "Check 4"; 
                        if (read.HasRows)
                        {
                            
                            Label13.Text = "Check 5";
                            while (read.Read())
                            {
                                status = read.GetValue(1).ToString();
                                Label13.Text = status;

                                if (status == "PASS")
                                {
                                    con.Close();
                                    PreChecking.Text = "  Checked : Serial Number passed in previous Station 1"; 
                                    PreChecking.ForeColor = Color.Green;
                                    YourText1 = "hi";
                                    

                                    ////catch WO and CASING SN should be in here
                                    if (textbox1.Text != "")
                                    {
                                        //Auto Capture the Work Order when Entering the serial Number
                                        con.Open();
                                        MySqlCommand cmd = new MySqlCommand("Select WorkOrder from db.workorder where @Text  between coalesce (StartRange, @Text) and Coalesce (EndRange, @Text)", con);
                                        cmd.Parameters.AddWithValue("@Text", textbox1.Text);
                                        MySqlDataReader sdr = cmd.ExecuteReader();
                                        //if the serial number is in the work order range, it will display the work order, else display error message
                                        if (sdr.HasRows)
                                        {
                                            while (sdr.Read())
                                            {
                                                TextBox3.Text = sdr.GetValue(0).ToString();
                                                label12.Text = "  Checked: Valid W/O for Serial Number";
                                                label12.ForeColor = Color.Green;
                                                DropDownList3.Focus();
                                                Button1.Enabled = true;
                                                Button1.Focus();
                                                //**Close pop-up message as requested by Engineers**//
                                                //Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' Done checking Board Serial Number and validity W/O ');", true);

                                            }
                                        }
                                        else
                                        {
                                            TextBox3.Text = "";
                                            textbox1.Focus();
                                            label12.Text = "Alert: Invalid W/O for Serial Number";
                                            YourText4 = "Hi";
                                            label12.ForeColor = Color.Red;
                                            Button1.Enabled = false;
                                            Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' 1 Please aware of Invalid W/O for current scan Serial Number');", true);
                                        }
                                        con.Close();
                                    }
                                }
                                else if (status == "FAIL")
                                {
                                    
                                    PreChecking.Text = "  Alert: Serial Number not pass in previous Station 1";
                                    PreChecking.ForeColor = Color.Red;
                                    label12.Text = string.Empty;
                                    DropDownList2.Enabled = false;
                                    DropDownList3.Enabled = false;
                                    Button1.Enabled = false;
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' Serial NUmber cannot pass this station');", true);
                                }
                            }
                        }
                        else
                        {
                            Label13.Text = "Bad Output";
                        }

                    }

Hope anyone can help and spot the mistake or have a solution.希望任何人都可以帮助并发现错误或有解决方案。 Thank you.谢谢你。

You can use order by to get the latest row top and with Limit 1 you can select only the first row.您可以使用 order by 来获取最新的行顶部,并且使用 Limit 1 您可以 select 仅第一行。

Select Status from db.station where SerialNumber = @SN and StationNumber = @Station order by CAST(Date_Time as DateTime) desc
limit 1

DB-Fiddle: DB-小提琴:

Schema and insert statements:模式和插入语句:

 create table station (SerialNumber varchar(50),    Date varchar(50),   Time varchar(50),   Date_Time varchar(50),  Status  varchar(50),StationNumber varchar(50));

 insert into station values('197601234512345'   ,'2021-04-28','11.53 AM'    ,'2021-04-28 11:53:00'  ,'PASS',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','11.54 AM',   '2021-04-28 11:54:00'   ,'FAIL',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','12.00 PM',   '2021-04-28 12:00:00'   ,'PASS',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','12.05 PM',   '2021-04-28 12:05:00'   ,'FAIL',    'Station 2');
 insert into station values('197601234512345'   ,'2021-04-28','12.10 PM',   '2021-04-28 12:10:00'   ,'PASS',    'Station 2');

Query:询问:

 Select Status from station where SerialNumber ='197601234512345'  and StationNumber = 'Station 1' order by CAST(Date_Time as DateTime) desc
 limit 1

Output: Output:

Status地位
PASS经过

db<fiddle here db<小提琴在这里

To get last rows for all SerialNumber use:要获取所有SerialNumber的最后一行,请使用:

MySQL 8+ MySQL 8+

WITH cte AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY SerialNumber ORDER BY Date_Time DESC) rn
              FROM db.station )
SELECT *
FROM cte
WHERE rn = 1;

MySQL 5+ MySQL 5+

SELECT db.station.*
FROM db.station
NATURAL JOIN ( SELECT SerialNumber, MAX(Date_Time) Date_Time
               FROM db.station
               GROUP BY SerialNumber ) maxdates

If you need these data for particular SerialNumber values only then add according WHERE clause.如果您只需要特定SerialNumber值的这些数据,则根据 WHERE 子句添加。

If you need the data not for SerialNumber but for (SerialNumber, StationNumber) then modify the queries accordingly.如果您需要的不是SerialNumber而是(SerialNumber, StationNumber)的数据,则相应地修改查询。

For single SerialNumber value - according WHERE and ORDER BY Date_Time DESC LIMIT 1 is enough.对于单个SerialNumber值 - 根据 WHERE 和ORDER BY Date_Time DESC LIMIT 1就足够了。

Solution: my situation kinda relate to situation that happen in enter link description here解决方案:我的情况有点与在此处输入链接描述中发生的情况有关

so, my new SQL command所以,我的新 SQL 命令

SELECT a.ID, a.Date_Time, a.Status FROM db.station a, (SELECT MAX(ID) as id  FROM db.station WHERE SerialNumber = @SN Group by StationNumber = @Station) b WHERE a.ID = b.id

I test to insert Serial Number 197601234512345 in Station 3 finally, it gets the latest row from the previous Station (Station 2)我最后测试在Station 3中插入序列号197601234512345,它从上一个Station(Station 2)获取最新行

ID ID SerialNumber序列号 Date日期 Time时间 Date_Time约会时间 Status地位 StationNumber电台编号
213942 213942 197601234512345 197601234512345 2021-04-28 2021-04-28 12.11 PM中午 12 点 11 分 2021-04-28 14:31:00 2021-04-28 14:31:00 PASS经过 Station 2 2号站

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM