如何修剪SQL语句的WHERE子句?

时间:2017-05-31 10:56:50

标签: c# sql asp.net sql-server ado.net

我正在尝试在SQL数据库中使用 datetime 列来检索 Start_Time 日期等于某个值的行。

这是我当前的SQL:

WHERE Start_Time

Start_Time 列的商店如下:26/05/2017 16:06:00

上面的子查询返回日期:26/05/2017。

我希望外部SELECT语句检索 Start_Time 以相同“日期”(2017年5月26日)开头的行,我现在想忽略时间方面。

目前,由于CREATE TABLE [dbo].[Shift] ( [Shift_Id] INT IDENTITY (1, 1) NOT NULL, [Start_Time] DATETIME NOT NULL, [End_Time] DATETIME NOT NULL, [Job_Type] NVARCHAR (50) NOT NULL, [Employee_Id] INT NOT NULL, [Available] INT NULL, FOREIGN KEY ([Employee_Id]) REFERENCES [dbo].[Employee] ([Employee_Id]) ON DELETE CASCADE ); 代码,这是失败的。目前没有修剪专栏的时间部分。

你们能告诉我如何删除WHERE子句中的时间方面吗?

   protected void repFullSchedule_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater jobRepeater = (Repeater)e.Item.FindControl("repJobs");
            string Start_time = DataBinder.Eval(e.Item.DataItem, "Start_Time").ToString();
            SqlCommand cmd = new SqlCommand("Select Job_Type FROM Shift WHERE cast(Start_Time as date) IN (SELECT DISTINCT CAST(Start_Time AS DATE) As Start_Time FROM Shift)", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);




            DataTable dt = new DataTable();
            sda.Fill(dt);
            jobRepeater.DataSource = dt;
            jobRepeater.DataBind();

        }
    }
}

另外,下面是我的完整代码:

react-transition-group

3 个答案:

答案 0 :(得分:0)

你可以在where子句和下面使用convert:

WHERE convert(date, Start_Time) IN(SELECT DISTINCT CAST(Start_Time AS DATE) As Start_Time FROM Shift)

答案 1 :(得分:0)

试试这个......

Select Job_Type FROM Shift WHERE cast(Start_Time as date) IN (SELECT DISTINCT CAST(Start_Time AS DATE) As Start_Time FROM Shift)

否则

Select Job_Type FROM Shift WHERE cast(convert(varchar(10),Start_Time,101) as date) IN (SELECT DISTINCT CAST(convert(varchar(10),Start_Time,101) AS DATE) As Start_Time FROM Shift)

答案 2 :(得分:0)

如果您要查找以特定日期开始的工作,那么我建议:

SELECT Job_Type
FROM Shift
WHERE CAST(Start_Time AS DATE) = '2017-05-26';

我不明白你想用" IN"做什么。您说:"选择所有在任何作业开始的日期开始的作业"。这与"选择其开始日期已知的所有作业"。

如果你想要只有一份工作的日子(可能由不必要的SELECT DISTINCT建议),那么你可以这样做:

SELECT MAX(Job_Type) as Job_Type
FROM Shift
GROUP BY CAST(Start_Time AS DATE)
HAVING COUNT(*) = 1;