1个包含日期的历史记录(日期) 1个账户类别账号(nvarchar(50)) 1表与账户余额(nvarchar(50)),日期(日期时间),余额(浮动)
我需要一个LINQ或SQL Server查询来从Balance中获取以下内容:
(历史记录中的每个日期的日期,帐户,余额),对于AccountInfo中的每个帐户,该日期下午4:10:00之前的最后一个记录的余额
下面的我的SQL会在下午4:10:00之前返回所有记录,但我只想要每个帐户的最后一个记录:
select [Date],Account,Balance from Balance where Account in (select Account from AccountCategories) and DATEADD(dd, 0, DATEDIFF(dd, 0, [Date])) in (select DATEADD(dd, 0, DATEDIFF(dd, 0, [Date])) from History) and [Date] <= DATEADD(mi,970,DATEADD(dd, DATEDIFF(dd, 0, [Date]), 0)) order by [Date] desc,Account
这个LINQ也没有得到我想要的东西'LINQ to Entities不支持指定的类型成员'Date'。仅支持初始值设定项,实体成员和实体导航属性。':
TimeSpan ts = new TimeSpan(16, 10, 0);
var accts = AccountCategories.Select(u => u.Account);
var pastDates = Histories.Select(u => u.Date);
var dailyBalance = (from dailyBal in Balances where accts.Contains(dailyBal.Account) group dailyBal by dailyBal.Account into a select a.OrderByDescending(t => t.Date).Where(u => u.Date <= (u.Date.Date + ts)).FirstOrDefault());
有什么想法吗?
答案 0 :(得分:0)
这里面临的挑战很大一部分是你正在改变从午夜到下午4:10的“日”边界。我的方法创建了一个名为WorkingDay
的新变量,此变量此时结束。它通过从[日期]减去(16 * 60 + 10)分钟然后再增加一天(以获得正确的相应日历日期)来实现此目的。
下一步是使用row_number()
选择每个工作日的最后一个值:
select WorkingDay, account, balance
from (select h.*,
ROW_NUMBER() over (partition by account, WorkingDay order by [date] desc) as seqnum
from (select h.*,
cast([date]+1-(16*60+10)/(24*60.0) as DATE) as WorkingDay
from history h
) h
) h
where seqnum = 1
答案 1 :(得分:0)
这是一个解决方案,在下午4:10之前为记录计算给定日期的row_number,然后在下午4:10之前仅返回余额记录
SELECT [date],
account,
balance
FROM (SELECT [date],
account,
balance,
Row_number()
OVER (
partition BY CONVERT(DATE, [date]), account
ORDER BY [date] DESC) AS seqnum
FROM balance
WHERE CONVERT(DATE, [date]) IN (SELECT CONVERT(DATE, [date])
FROM history)
AND account IN (SELECT account
FROM accountcategories)
AND [date] <= Dateadd(mi, 970, CONVERT(DATETIME,
CONVERT(DATE, [date])))
) t1
WHERE seqnum = 1