我正在尝试运行以下MS SQL查询:
select PolicyCode, OccupancyCode, premiumcode, VersionNumber, rate
from COVERAGE_RATES as cov
group by PolicyCode, OccupancyCode, PremiumCode,VersionNumber, rate
having (VersionNumber = 25 or VersionNumber =
(
select MAX(versionnumber) from COVERAGE_RATES where
PolicyCode = 4 and OccupancyCode=2 and PremiumCode = cov.PremiumCode
) ) and PolicyCode = 4
AND OccupancyCode = 2
想法是记录VersionNumber为25的记录,或者如果组中没有这样的版本,则取最大数字。那就是我们有表:
policyCode Version ...
----------------------
1 2
1 10
2 1
2 25
2 26
我们应该得到以下结果:
policyCode Version ...
----------------------
1 10
2 25
Linq代码是:
var res = (from c in CoverageRate
group c by c.PolicyCode
into rateGroup
where rateGroup.Any(r => r.VersionNumber == versionNumber ||
r.VersionNumber ==
CoverageRate.Where(c2 => c2.OccupancyCode == occupancyCode && c2.PolicyCode == policyCode)
.Max(c2 => c2.VersionNumber))
select rateGroup);
但我想我做错了,因为当我尝试接受res.Count()时出现以下错误:
无法创建类型'..CoverageRate'的常量值。在此上下文中仅支持原始类型(例如Int32,String和Guid')。
有人可以帮我解决这个问题吗?
答案 0 :(得分:3)
更新 - 我认为您正在寻找:
var res = from c in CoverageRate
group c by c.PolicyCode into rateGroup
select rateGroup.OrderByDescending(x => x.VersionNumber)
.FirstOrDefault();
答案 1 :(得分:1)
from c in CoverageRate
group c by c.PolicyCode
into g
select new
{
policyCode = g.Key,
Version = (from t2 in g select t2.VersionNumber).Max()
}