繁体   English   中英

按日期从交易表中获取最后一笔交易

[英]Get last transactions from Transaction table by date

我需要从2个lats日期(此交易完成)中的“交易表”中获取交易。 并检查最后一天的交易额是否比前一天的交易额多10%。 我的表具有“帐户ID”,“子帐户ID”,“金额”,“日期”和“用户ID”列。 例如:

CREATE TABLE Transactions
    (`id` int, `AccountId` int, `SubAccountId` int, `Amount` decimal 
         ,`Date` datetime, `User` int);

INSERT INTO Transactions
    (`id`, `AccountId`, `SubAccountId`, `Amount`, `Date`, `User`)
VALUES
    (1, 1, 2, 100, '06/15/2018', 1),
    (2, 1, 2, 40, '06/15/2018', 1),
    (3, 1, 2, 20, '06/14/2018', 1),
    (4, 1, 2, 0, '06/10/2018', 1),
;

在此示例中,我只需要选择日期为06/15/2018和06/14/2018的交易,并显示该天的交易金额之和。 到目前为止,我可以选择最后一笔交易,如下所示:

select distinct AccountId, 
    SubAccountId,
    UserId,
    Amount, 
    Date AS lastDate,
    min(Date) 
        over (partition by PayerAccount order by Date 
            rows between 1 preceding and 1 preceding) as PrevDate
from Transactions
order by UserId
with CTE1 as
(
select accountID, Date, sum(Amount) as Amount
from Transactions
where Date between '2018-06-14' and '2018-06-16' -- Apply date restriction here
group by accountID, Date
)
, CTE2 as
(
select accountID, Amount, Date,
       row_number() over (partition by accountID order by date desc) as rn
from Transactions
)
select a1.accountID, a1.Amount, a1.Date, a2.Date, a2.Amount
from CTE2 a1
left join CTE2 a2
on a1.accountID = a2.accountID
and a2.rn = a1.rn+1

这将通过一行上的accountID为您提供每天和前一天的交易。 从这里您可以比较值。

这种检查sum amount对当天的sum amount的前一天(以确认它是大于10%),然后做了top 2只提取最后两天...

WITH CTE AS(
    select
        Date,
        sum(Amount) as SumAmount,
        rownum = ROW_NUMBER() OVER(ORDER BY Date)
    from Transactions
    group by Date
)
select top 2 CTE.date, CTE.SumAmount, CTE.rownum, CASE WHEN prev.sumamount > CTE.sumamount * 0.10 THEN 1 else 0 END isgreaterthan10per
from CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
order by CTE.date desc

您想按日期分组并求和

select Date,sum(Amount) from Transactions /*where contitions*/ group by Date

您可以使用它。 希望对您有帮助。

SELECT 
*
FROM Transactions tb
INNER JOIN 
(
  SELECT MAX([Date]) AS [Date] FROM Transactions

  UNION ALL 

  SELECT MAX([Date]) AS [Date] FROM Transactions WHERE [Date] < (SELECT MAX([Date]) AS [Date] FROM Transactions)

) tb1 ON tb1.[Date] = tb.[Date]

您可以在下面的查询中查询以获取最后两个日期以及这两个日期的金额总和。

从日期> =(从日期<(从交易中选择max(date))的交易中选择最大(日期)的交易中选择不同的账户id,subaccountid,用户,过渡,总和(金额按日期划分)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM