如何在SQL Server查询中获取第一行值

时间:2018-07-31 04:36:39

标签: sql sql-server stored-procedures

我的要求是使用最新的 PaymentID 的任何最新的 postdate 的AllowedAmount。我尝试了很多次只是为了获得firstrow的值。但是我却得到了2行。使用 rownumber(),但在选择所有患者姓名后不适用,它不会提供正确的输出。除了 top 1 之外,还有其他方法吗? rownumber()分区我的要求是获取一个具有AllowedAmount的ChargeID,用于具有最新PaymentID的最新Postdate

SELECT
DISTINCT
  TM.[PatientName] AS [PATIENT NAME],
  [dbo].[SplitString](TM.InsPlanName, '(') AS [ Insurance],
  ISNULL(TMmm1.ChargeAmount, 0) AS [Amount Billed],
  ISNULL(TMM1.AllowedAmount, 0) AS AllowedAmount,
  TMM1.PostDate,
  TMM1.PaymentID,
  TM.ChargeID AS ChargeID

FROM [MasterReport] AS TM
LEFT OUTER JOIN (SELECT
  SUM(ISNULL(ChargeAmount, 0)) AS ChargeAmount,
  [ChargeID]
FROM [dbo].[TransactionMasterReport]
WHERE transactiontype = 'Charges'
GROUP BY [ChargeID]) AS TMmm1
  ON TM.ChargeID = TMmm1.ChargeID


LEFT OUTER JOIN (SELECT DISTINCT
  MAX(PostDate) AS PostDate,
  MAX(ISNULL(PaymentID, 0)) AS PaymentID,
  [ChargeID],
  AllowedAmount
FROM [dbo].[TransactionMasterReport]
WHERE ([TransactionType] = 'Payments'
OR [TransactionType] = 'Adjustments')
AND AllowedAmount >= 1
AND PaymentSource LIKE '%Primary%'
GROUP BY [ChargeID],
         PostDate,
         AllowedAmount,
         PaymentID) AS TMM1
  ON TM.[ChargeID] = TMM1.[ChargeID]

WHERE TM.ChargeId = 4255

ORDER BY TM.[ChargeID]

ouput

当我在左外部联接中使用前1个时,我获得的允许金额为0.00,这是不正确的。

3 个答案:

答案 0 :(得分:2)

在处理语法错误后应该可以使用。我没有与您匹配的表或数据。更改位于第二个LeftJoin中,以使用按字段降序排序的Row_Number。您可能需要将整个内容封装在另一个Select(...)中,然后将RN1 = 1移到其下。

The output of the above code is coming out to be this:

Commitment
Commitment
Commitment
Commitment
Commitment

答案 1 :(得分:0)

我们不知道实际的情况,但是应该像suggested above那样工作,但是正如您所说的,它再次返回相同的输出,因此请使用查询作为subquery,如下所示,并尝试

从整个输出中仅返回一条记录

SELECT TOP 1 *
FROM ( <your query> )
ORDER BY postdate, paymentid DESC

要返回每个top 1的{​​{1}}值

ChargeID

答案 2 :(得分:0)

我认为,您应该像这样更改查询

SELECT TOP 1 <your fields>
FROM [MasterReport] AS TM
LEFT OUTER JOIN  <TMmm1> ON TM.ChargeID = TMmm1.ChargeID
LEFT OUTER JOIN  <TMM1> ON TM.[ChargeID] = TMM1.[ChargeID]
WHERE TM.ChargeId = 4255
ORDER BY TMM1.PostDate DESC, TMM1.PaymentID DESC

它只会给您一行(TOP 1),它将是最新的PostDatePaymentID