根据mysql表中的同一个月计算date列

v64noz0r  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(367)

假设我有一个mysql表,其中包含empid和date列。我要数一数同一个月的日期。例如,如果empid在表中有4个来自同一个月的日期,则应触发一封电子邮件

using (MySqlConnection con = new MySqlConnection(serverstring))
{
     con.Open();
     string query = "SELECT COUNT(empID) FROM tblnm WHERE empID=@eid date=date";
     MySqlCommand cmd = new MySqlCommand(query, con);
     cmd.Parameters.AddWithValue("@eid", lbleid.Text);
     string cnt = cmd.ExecuteScalar().ToString();
     var count = Convert.ToInt32(cnt);
     if(count >= 4)
     {
         triggerEmail();
     }
}

所以这个月可以是未来的任何一个月,但是如果有超过或等于4个数据具有相同的empid在任何一个月的查询应该检查它和电子邮件必须被触发。我要怎么做?提前谢谢。。。。

w51jfk4q

w51jfk4q1#

您可以执行以下查询:

SELECT COUNT(empID)
FROM tblnm
WHERE year(date) = year(@date) and month(date) = month(@date);

但我会说,如果你想知道哪个empid有4个以上的条目:

SELECT empID, COUNT(*)
FROM tblnm
WHERE year(date) = year(@date) and month(date) = month(@date)
group by empID;
nfg76nw0

nfg76nw02#

mysql拥有 LAST_DAY() 可与组合使用的函数 GROUP BY / HAVING 在同一个月内容易获得计数的条款:

SELECT EmpID, LAST_DAY(`Date`) AS Month, COUNT(*) As NumEntries
FROM tblnm 
WHERE EmpID = @EmpID
GROUP BY EmpID, LAST_DAY(`Date`)
HAVING COUNT(*) >= 4

像这样使用:

string query = @"
    SELECT EmpID, LAST_DAY(`Date`) AS Month, COUNT(*) As NumEntries
    FROM tblnm 
    WHERE EmpID = @EmpID
    GROUP BY EmpID, LAST_DAY(`Date`)
    HAVING COUNT(*) >= 4;";

using (var con = new MySqlConnection(serverstring))
using (var cmd = new MySqlCommand(query, con))
{
    cmd.Parameters.Add("@EmpID", MySqlDbType.Int32).Value = Convert.ToInt32(lbleid.Text);
    con.Open();
    using (MySqlDataReader rdr = cmd.ExecuteReader())
    {     
        while(rdr.Read())
        {
           triggerEmail(rdr["EmpID"], (int)rdr["NumEntries"]);
        }
    }
}

相关问题