【发布时间】:2016-07-03 20:07:56
【问题描述】:
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 而无需子选择?
【问题讨论】:
-
您也可以只使用
OUTER APPLY或CROSS APPLY使用该给定值计算给定日期之前的所有内容,这在技术上不是子选择。 -
@ZLK,你能举个例子吗?也许是另一种答案?
-
你可以把你的子查询写成一个应用,比如
SELECT Z.PriorCount, mt1.TheDate, mt2.TheValue FROM MyTable mt1 CROSS APPLY (SELECT COUNT(*) FROM MyTable WHERE TheValue = mt1.TheValue AND TheDate < mt1.TheDate) Z(PriorCount) WHERE... -
@ZLK - 交叉应用也可以;也许考虑将其添加为替代答案。
标签: sql sql-server azure-sql-database sql-server-2016