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

时间:2016-07-03 20:07:57

标签: sql sql-server azure-sql-database sql-server-2016

SQL Azure数据库V12(SQL Server 2016)

给出以下基本表结构:

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,但无法提出任何可以返回先前计数的内容。是否有替代SQL查询在没有子选择的情况下返回PriorCount

1 个答案:

答案 0 :(得分:2)

您可以将comment_thread_idCOUNT子句一起使用:

ORDER 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