我有一张表,其中ID可以与多个帐单相关联。我需要做的是找到MAX
结算金额,ID和最高(MAX
)帐单的日期。问题是,在任何特定日期都可能有成千上万的人,数百人。
我的查询
select patientID, max(amountPaid) as maxPaid
from myTable
group by patientID
给我我需要的东西,减去日期。我试图解决这个问题是
select t.patientID, t.maxPaid, myTable.billDate
from myTable
inner join
(
select patientid, max(amountPaid) as maxPaid
from myTable
group by patientID
) as t on t.patientID=myTable.patientID and =t.maxPaid=myTable.maxPaid
给出的错误是invalid column name maxPaid
。我尝试不给计算字段一个别名,但SQL Server也不接受myTable.max(amountPaid)。解决这个问题的最快方法是什么?提前谢谢。
答案 0 :(得分:4)
您当前的方法存在的问题是,如果患者有两张最大金额的账单,您将同时获得这两种账单。
请改为尝试:
SELECT
patientid,
amountPaid AS max_paid,
billDate
FROM
(
SELECT
patientid,
amountPaid,
billDate,
ROW_NUMBER() OVER (PARTITION BY patientid
ORDER BY amountpaid DESC) AS RowNumber
FROM myTable
) T1
WHERE T1.RowNumber = 1
即使患者有两张具有相同最大值amountpaid
的账单,每位患者也会返回一行。
答案 1 :(得分:2)
;WITH x AS (SELECT PatientID, BillDate, AmountPaid,
rn = ROW_NUMBER() OVER (PARTITION BY PatientID ORDER BY AmountPaid DESC)
FROM dbo.myTable
)
SELECT PatientID, BillDate, AmountPaid
FROM x
WHERE rn = 1;
答案 2 :(得分:1)
根据您的描述,我认为您的意思是:
select t1.patientID, t2.maxPaid, t1.billDate
from myTable t1
inner join
(
select patientid, max(amountPaid) as maxPaid
from myTable
group by patientID
) t2
on t1.patientID=t2.patientID
and t1.amountPaid=t2.maxPaid