我有一个存储过程,它从我的数据库中获取提交条目以及每个条目引发了多少。我想要获得" Rank"提交的数量基于所提出的金额与所有其他提交的数量。
第二次回归应该是等级1,因为它的总增加量比第一次应该是等级2的记录要高。我接近了吗?
我的sp:
SELECT A.[id],
A.[petName],
A.[petCaption],
B.[petType],
C.[FirstName] as ownerFirstName,
C.[LastName] as ownerLastName,
D.[imageName],
(
SELECT CONVERT(varchar(20),sum(transactionAmount), 1) as totalRaised,
RANK() OVER (ORDER BY sum(transactionAmount) DESC) AS Rank
FROM petContestTransactions
WHERE submissionID = A.[id] and paymentType = 'donation'
FOR XML PATH ('transactionDetails'), TYPE, ELEMENTS
)
FROM petContestSubmissions as A
JOIN petContestTypes as B
ON A.[petType] = B.[id]
JOIN EmpTable as C
ON A.[empID] = C.EmpID
JOIN petContestImages as D
ON A.[image] = D.[submissionID]
JOIN petContestTransactions as E
ON E.[submissionID] = A.[id]
WHERE E.[transactionStatus] = 'completed' and E.[paymentType] = 'submission'
FOR XML PATH ('submission'), TYPE, ELEMENTS, ROOT ('root');
返回XML:
<root>
<submission>
<id>1</id>
<petName>Nala</petName>
<petCaption>Shes a wonder pup!</petCaption>
<petType>Dog</petType>
<ownerFirstName>Carl</ownerFirstName>
<ownerLastName>H</ownerLastName>
<imageName>nalaHUS123.png</imageName>
<transactionDetails>
<totalRaised>130.00</totalRaised>
<Rank>1</Rank>
</transactionDetails>
</submission>
<submission>
<id>2</id>
<petName>Simba</petName>
<petCaption>Shes a wonder pup!</petCaption>
<petType>Cat</petType>
<ownerFirstName>Carl</ownerFirstName>
<ownerLastName>H</ownerLastName>
<imageName>simbaHUS123.png</imageName>
<transactionDetails>
<totalRaised>250.00</totalRaised>
<Rank>1</Rank>
</transactionDetails>
</submission>
</root>
答案 0 :(得分:0)
SELECT A.[id],
A.[petName],
A.[petCaption],
B.[petType],
C.[FirstName] as ownerFirstName,
C.[LastName] as ownerLastName,
D.[imageName],
RANK() OVER (ORDER BY sum(F.totalRaised) DESC) AS Rank
FROM petContestSubmissions as A
JOIN petContestTypes as B
ON A.[petType] = B.[id]
JOIN EmpTable as C
ON A.[empID] = C.EmpID
JOIN petContestImages as D
ON A.[image] = D.[submissionID]
JOIN petContestTransactions as E
ON E.[submissionID] = A.[id]
OUTER APPLY
(
SELECT sum(transactionAmount) as totalRaised,
FROM petContestTransactions pt
WHERE pt.submissionID = A.[id] and pt.paymentType = 'donation'
) F
WHERE E.[transactionStatus] = 'completed' and E.[paymentType] = 'submission'
FOR XML PATH ('submission'), TYPE, ELEMENTS, ROOT ('root');
我使用外部申请获得totalRaised然后你可以直接排名。