这是我的表[Property]:
Loanno Balance amount PropertyType
-------------------------------------
1001045 308731.770000 1
1001045 2007700.740000 2
1001045 3087318905.770 3
1001045 308731.770000 4
1001046 306589.67 1
1001046 456321.23 1
1001046 6932542.89 1
1001047 965421.34 Null
1001047 965421.34 2
1001048 567894.34 1
1001048 567894.34 2
我必须获得[Loanno]
最高balance amount
的属性类型。如果最高balance amount
中存在平局且Property type
的{{1}}与loannumber
不同,那么Loan number
我必须将property type
填充为&# 39; 8&#39 ;.所以我的最终输出应该如下所示:
Loanno PropertyType
---------------------
1001045 3
1001046 1
1001047 1
1001048 8
这是我试过的查询。这是@Gord建议的。
SELECT DISTINCT
[Property].Loanno,
IIf(Loanno_MaxBalance_Count.RowCount>1, 8, [Property].PropertyType) AS PropertyType
FROM
[Property]
INNER JOIN
(
SELECT
[Property].Loanno,
[Property].[Balance amount],
COUNT(*) AS RowCount
FROM
[Property]
INNER JOIN
(
SELECT
Loanno,
MAX([Balance amount]) AS MaxBalance
FROM [Property]
GROUP BY Loanno
) AS Loanno_MaxBalance
ON Loanno_MaxBalance.Loanno=[Property].Loanno
AND Loanno_MaxBalance.MaxBalance=[Property].[Balance amount]
GROUP BY [Property].Loanno, [Property].[Balance amount]
) AS Loanno_MaxBalance_Count
ON [Property].Loanno=Loanno_MaxBalance_Count.Loanno
AND [Property].[Balance amount]=Loanno_MaxBalance_Count.[Balance amount]
但问题出在Loan no
1001047 ,最高Balance amount
965421.34 的Property type
为 1 和 NULL 。因此,对于此,上述查询将property type
作为 8 返回。相反,我希望它为1.一般情况下,如果balance amount
不同,Property type
最高,如果它不为空,我想 8 。否则property type
应为非NULL值。
任何有关这方面的帮助将不胜感激。
答案 0 :(得分:0)
这样做你想要的吗?
select LoanNo,
iif(min(PropertyType) = max(PropertyType), min(PropertyType), 8) as PropertyType
from property as p inner join
(select LoanNo, max(BalanceAmount) as maxba
from property
group by LoanNo
) as pmax
on p.LoanNo = pmax.LoanNo and p.BalanceAMount = pmax.maxba
group by LoanNo;