可以消除这个子查询?

时间:2013-04-05 06:31:39

标签: sql sql-server tsql sql-server-2012

我有一个说明字段为

的文件表
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

JurisdictionIDDocumentStatusID上有索引。罪魁祸首是子查询 - 我试图计算CanChangeStatus的方式。有什么方法可以加快速度或将此子查询转换为连接,因为连接主要比子查询更快?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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