SQL 2014如何从一天发生的事件中提取数据?

时间:2019-02-09 01:04:32

标签: sql sql-server

SQL Server Express 2014 ---您好,我对SQL和进行查询非常陌生。基本上,我希望提取在同一天开始和结束的事件。

*正在询问的问题:“在“参与度”表中,显示同一天内开始和停止的所有参与度。” 24小时之间发生的事件。

我似乎无法编写正确的语法。到目前为止我的进度...

SELECT EngagementNumber,StartDate, StartTime, Stoptime, 
FROM Engagements
WHERE CAST(Stoptime-Starttime AS INTERGER)=1

1 个答案:

答案 0 :(得分:-1)

发布SQL查询问题时,始终最好提供数据样本和一些有关字段的表信息。

我在下面包括的是一些基于原始查询的查询,这些查询都旨在以略有不同的方式显示该数据集。

在旁注。我不确定为什么您的where子句中有Stoptime-Starttime并保留了它。但是我确实讨厌在where子句中有聚合。这是个人选择,但可能要牢记,我通常使用其他子句,例如“ HAVING”。

下面是查询集,请告诉我其中的一个是否适合您的目的,如果需要,我可以进行扩展。

---- Your original query (You had and extra , in there)
SELECT 
    EngagementNumber,
    StartDate, 
    StartTime, 
    Stoptime
FROM Engagements
WHERE 
    CAST(Stoptime-Starttime AS INTERGER)=1

---- This will Get all events on the day, take their stop and start then sum all of it together
---- This might not be what you want, its handy for counting how many events are on a day or
---- the total effect of a day, with a group by you must be working with aggregates
SELECT 
    StartDate, 
    COUNT(EngagementNumber) AS NumberofEvents,
    SUM(Stoptime-Starttime) AS TotalTimeTaken
FROM Engagements
WHERE 
    CAST(Stoptime-Starttime AS INTERGER)=1
GROUP BY
    StartDate

---- This will pull all the values and sort them by date
---- It will give you a line for every Engagement but list all the 01/01 and then 02/01
SELECT 
    EngagementNumber,
    StartDate, 
    StartTime, 
    Stoptime
FROM Engagements
WHERE 
    CAST(Stoptime-Starttime AS INTERGER)=1
ORDER BY 
    StartDate

---- This includes a Date parameter in the where clause to allow you to bring
---- back a single day of engagements.
SELECT 
    EngagementNumber,
    StartDate, 
    StartTime, 
    Stoptime
FROM Engagements
WHERE 
    CAST(Stoptime-Starttime AS INTERGER)=1
    AND StartDate = ?