需要帮助从数据示例创建SQL查询

时间:2014-12-09 11:51:55

标签: sql sql-server sql-server-2008

我有一个数据库表。

database table

我想得到所有DBKey的列表:至少有一个Staled = 1的条目,最后一个条目是Staled = 0

列表不应包含仅Staled = 0或Staled = 1的DBKey。

在此示例中,列表将为:DBKey = 2和DBKey = 3

3 个答案:

答案 0 :(得分:1)

我认为这应该可以解决问题:

SELECT DISTINCT T.DBKey
FROM TABLE T
WHERE
    -- checks that the DBKey has at least one entry with Staled = 1 
    EXISTS (
        SELECT DISTINCT Staled
        FROM TABLE
        WHERE DBKey = T.DBKey
            AND Staled = 1
        )
    -- checks that the last Staled entry for this DBKey is 0
    AND EXISTS (
        SELECT DISTINCT Staled
        FROM TABLE
        WHERE DBKey = T.DBKey
            AND Staled = 0
            AND EntryDateTime = (
                SELECT MAX(EntryDateTime)
                FROM TABLE
                WHERE DBKey = T.DBKey
                )
        )

以下是查询的有效SQLFiddle,使用您的示例数据。

我们的想法是使用EXISTS来查找您所描述的那些个别条件。我已经在代码中添加了注释来解释每个代码的作用。

答案 1 :(得分:1)

应该使用简单的JOIN来完成...使用任何1个限定符开始FIRST,通过相同的键和0 staled限定符连接到自身并且0记录具有更高的日期。确保您有一个索引(DBKey,Staled,EntryDateTime)

SELECT
      YT.DBKey,
      MAX( YT.EntryDateTime ) as MaxStaled1,
      MAX( YT2.EntryDateTime ) as MaxStaled0
   from
      YourTable YT
         JOIN YourTable YT2
            ON YT.DBKey = YT2.DBKey
            AND YT2.Staled = 0
            AND YT.EntryDateTime < YT2.EntryDateTime
   where
      YT.Staled = 1
   group by 
      YT.DBKey
   having
      MAX( YT.EntryDateTime ) < MAX( YT2.EntryDateTime ) 

答案 2 :(得分:0)

也许这个:

With X as
(
    Select Row_Number() Over (Partition By DBKey Order By EntryDateTime Desc) RN, DBKey, Staled
    From table
)
Select * 
From X 
Where rn = 1 and staled = 0 and
    Exists (select 1 from x x2 where x2.dbkey = x.dbkey and Staled = 1)