SQL 返回先前匹配记录的子查询的替代方法

Alternative to SQL Sub Query for Returning Prior Matching Records

SQL Azure 数据库 V12(SQL 服务器 2016)

给定以下基本 table 结构:

MyTable
==============
Id int PK
TheDate datetime2 not null
TheValue varchar(50) not null
-- other fields

以及以下 SQL:

select 
    (   select count(*) 
        from MyTable mt2 
        where 
            mt2.TheValue = mt1.TheValue
            and mt2.TheDate < mt1.TheDate
    ) as PriorCount
    , mt1.TheDate, mt1.TheValue 
from MyTable mt1
where mt1.TheDate between '2016-01-01' and '2017-01-01'
order by mt1.TheDate desc

示例输出:

PriorCount   TheDate                 TheValue
===============================================
   1         2016-06-01 00:00:00     Foo
   2         2016-05-01 00:00:00     Bar
   1         2016-04-01 00:00:00     Bar
   0         2016-03-01 00:00:00     Foo
   0         2016-02-01 00:00:00     Bar

我已经查看了 OVER Clause,但无法对 return 先前的计数提出任何建议。是否有替代 SQL 查询 return PriorCount 而没有子 select?

您可以将 COUNTORDER BY 子句一起使用:

select count(*) over (partition by TheValue order by TheDate) - 1 as PriorCount,
       mt1.TheDate, mt1.TheValue 
from MyTable mt1
where mt1.TheDate between '2016-01-01' and '2017-01-01'
order by mt1.TheDate desc

编辑:

如果你想把COUNT应用到整个table,那么你可以使用下面的查询:

select PriorCount, TheDate, TheValue
from (
   select count(*) over (partition by TheValue 
                         order by TheDate) - 1 as PriorCount,
          TheDate, TheValue 
   from MyTable 
   order by TheDate desc) as t
where t.TheDate between '2016-01-01' and '2017-01-01'