我有一个查询,根据文档类型提取单个记录。我需要更改它以为特定“案例”提取ID列的最低值,或者如果文档类型为“Deed”。可能有多个“契约”记录,我们需要所有这些记录。目前它只提取“主要契约”。我该怎么做?
SELECT
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM
Documents
WHERE
(CaseNumberKey = @CaseNumberKey)
AND (DocType = 'Deed')
答案 0 :(得分:1)
这个问题有点令人困惑。你说你需要它来提取最低个案数字,或任何DocType为'Deed'的东西,但是你显示的查询实际上是任何具有所请求的案例编号的东西,并且DocType为'Deed'。它根本不看最低限度?什么是'主要行为',以及@CaseNumberKey来自什么?这是一个传递给内联函数或过程的参数,还是基于之前的某些内容计算的?
从您想要的声音开始,假设您正在运行2008或更高版本,请查看OVER子句以及MIN功能。可能会有类似下面的内容吗?
SELECT
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM
(SELECT
ROW_NUMBER() OVER(PARTITION BY CaseNumberKey ORDER BY DocIDKey ASC) AS Row_Num,
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM Documents
WHERE CaseNumberKey = @CaseNumberKey AND DocType = 'Deed') sub
WHERE Row_Num = 1
这应该为您提供与最低DocIDKey值相关联的行,其中CaseNumberKey =提供的值,DocType ='Deed'。基本上,它的作用是首先(在子查询中)按DocIDKey对所有内容进行排序,并根据排序为每行提供Row_Number,然后仅对第一个排序行进行过滤。
(注意:“PARTITION BY CaseNumberKey”部分是可选的,因为您已经按CaseNumberKey过滤了。)
编辑:修改后的版本(看到下面的评论后):
SELECT
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM
(SELECT
ROW_NUMBER() OVER(PARTITION BY CaseNumberKey ORDER BY DocIDKey ASC) AS Row_Num,
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM Documents
WHERE CaseNumberKey = @CaseNumberKey) sub
WHERE Row_Num = 1
UNION SELECT
DocIDKey, CaseNumberKey, Grantee, Grantor,
DocID, DocDate, RecDate, PrimaryDocID, RelatedDocID,
Interest, DocAmt, DocPath, DocType
FROM Documents
WHERE CaseNumberKey = @CaseNumberKey AND DocType = 'Deed'
^这应该为您提供第一个文档(具有最低DocIDKey的文档),以及指定CaseNumberKey的所有类型为'Deed'的文档。