1

1 表 History with Date (date) 1 table AccountCategories with Account (nvarchar(50)) 1 table Balance with Account(nvarchar(50)), Date(datetime), Balance(float)

我需要一个 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());

有任何想法吗?

4

2 回答 2

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
于 2013-04-19T19:04:53.293 回答
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 
于 2013-04-19T19:54:11.547 回答