从Mysql表基于同一月份对Date列进行计数

时间:2018-10-09 14:28:18

标签: c# mysql

可以说我有一个带有empID和date列的MySql表。我想获取日期来自同一月份的empID的计数。例如,如果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();
     }
}

因此该月可以是未来几个月的任何月份,但是如果在任何一个月份中有empID相同的empID大于或等于4个数据,则查询应进行检查,并且必须触发电子邮件。我该怎么办?预先感谢...。

2 个答案:

答案 0 :(得分:1)

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"]);
        }
    }
}

答案 1 :(得分:0)

您可以使用此查询:

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

但是,我想说的是,如果您想知道哪个empID具有四个以上的条目:

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