0

我有一个文档表,其中的字段为

DocumentID int - PK and autoincrement 
LastStatusChangedDateTime - datetime 
JurisdictionID - int 
DocumentStatusID - int

现在我想引入一个名为CanChangeStatus. 这就像一个队列。因此,如果文档是第一个,则可以更改其状态。这是我的查询:

Select d.DocumentID,  
(
    Select Cast(Case When d.DocumentID = v.DocumentID Then 1 Else 0 End as bit)
    From
    (
        Select Top 1 DocumentID
        From Documents
        Where JurisdictionID = d.JurisdictionID
            And
        DocumentStatusID = d.DocumentStatusID
        Order By LastStatusChangedDateTime 
    ) v
) as CanChangeStatus    
From Documents d

索引在JurisdictionID和上DocumentStatusID。罪魁祸首是子查询 - 我试图计算的方式CanChangeStatus。有什么办法可以加快速度或将此子查询转换为联接,因为联接大多比子查询快?

4

2 回答 2

5

您应该能够使用聚合函数(SQLFiddle上的示例)来执行此操作:

SELECT DocumentID,
       CASE WHEN ROW_NUMBER() OVER ( PARTITION BY JurisdictionID, DocumentStatusID
                                     ORDER BY LastStatusChangedDateTime )
         = 1 THEN 1 ELSE 0 END AS Bit 
FROM Documents
于 2013-04-05T06:40:38.860 回答
0
Select Cast(Case When TOP_DocumentID = DocumentID Then 1 Else 0 End as bit), DOCUMENTID
FROM
(
Select TOP 1 DOCUMENT_ID TOP_DocumentID, D.DOCUMENTID
From Documents d, DOCUMENTS J
Where J.JurisdictionID = d.JurisdictionID
And J.DocumentStatusID = d.DocumentStatusID
Order By J.LastStatusChangedDateTime 
) A
于 2013-04-05T06:38:30.907 回答