带有其他信息的SQL查询

时间:2014-04-04 06:48:36

标签: sql

我有一个RDB,有一些观察。所以我有一个beginTimestamp和一个endTimestamp。现在我想要一个特殊时间段的所有观察+一个带有布尔值的额外单元格,如果它是第一个观察,则为真。

我的表格结构如下所示:

ID  | Bird | beginTimestamp | endTimestamp
********************************************
101 | 125  | 3.4.2014 12:30 | 3.4.2014 12:33 //first Observation of this bird
102 | 125  | 3.4.2014 14:15 | 3.4.2014 14:27 //second Observation of this bird
103 | 126  | 3.4.2014 12:31 | 3.4.2014 12:45 //5th Observation of this bird

所以现在我想知道有多少新的' knwon'时间段内的鸟类:3.4.2014 12:31 - 3.4.2014 12:32

在这种情况下,1个新的和1个已知的'

这样的事情可能吗?怎么样?

2 个答案:

答案 0 :(得分:1)

以下是SQL Server的示例:

 SELECT O.Bird, O.beginTimestamp, O.endTimestamp,
        CASE
            WHEN FS.firstSeenTimestamp = O.beginTimestamp THEN 'True'
            ELSE 'False'
        END AS IsFirstTimeSeen
   FROM Observations AS O
        LEFT JOIN
        (
        -- Identify first instance of each bird being seen
         SELECT Bird, MIN(beginTimestamp) AS firstSeenTimestamp
           FROM Observations
          GROUP BY Bird
        ) AS FS
        ON FS.Bird = O.Bird

我们确定第一次"已知"在LEFT JOIN中已经看到了鸟,我们使用CASE语句附加额外的列,指示它是否第一次被看到。

我已经使用过' True'并且'错误'为了便于阅读,但通常我会分别使用1和0来表示True和False。

- =编辑= -

在更新问题后,您可以使用以下内容获取指定日期范围内每只鸟的计数:

DECLARE @RangeStart DATETIME
DECLARE @RangeEnd DATETIME
SET @RangeStart = '2014-04-03T00:00:00'
SET @RangeEnd = '2014-04-03T23:59:59'

 SELECT O.Bird,
        SUM (CASE
            WHEN O.beginTimestamp = FS.firstSeenTimestamp THEN 1
            ELSE 0
        END) AS CountOfFirstSeen,
        SUM (CASE
            WHEN O.beginTimestamp > FS.firstSeenTimestamp THEN 1
            ELSE 0
        END) AS CountOfSeenAgain
   FROM Observations AS O
        LEFT JOIN
        (
        -- Identify first instance of each bird being seen
         SELECT Bird, MIN(beginTimestamp) AS firstSeenTimestamp
           FROM Observations
          GROUP BY Bird
        ) AS FS
        ON FS.Bird = O.Bird
  WHERE O.beginTimestamp BETWEEN @RangeStart AND @RangeEnd
  GROUP BY O.Bird

答案 1 :(得分:1)

您可以使用此LOGIC,要获得清晰的图片,请查看 SQL Fiddle

select a.*, 'Observation no ' + Cast(oldRecs.beforThis as Varchar(10))  + ' for this bird'  from joborder as a
outer apply
    (
        select COUNT(jo_no) + 1 as beforThis from joborder as b
        where b.jo_no < a.jo_no
            and b.jo_status = a.jo_status
    )as oldRecs