我需要从交易表中获取交易表的交易,这些交易完成了。并检查,如果最后一天的交易金额超过前一天交易金额的10%。 我的表有列AccountId,SubAccountId,Amount,Date和UserId。 例如:
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
答案 0 :(得分:1)
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获取每天的交易和前一天的交易。从这里你可以比较价值。
答案 1 :(得分:1)
这会检查当天的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
答案 2 :(得分:0)
你想按日期分组并总结金额
select Date,sum(Amount) from Transactions /*where contitions*/ group by Date
答案 3 :(得分:0)
你可以用它。我希望它适合你。
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]
答案 4 :(得分:0)
您可以查看以下查询,以获取这两个日期的最后两个日期和金额总和。
选择明显的accountid,subaccountid,user,trandate,sum(amount)over(按日期划分) 来自交易 其中date&gt; =(从日期&lt;(从交易中选择max(date))的交易中选择max(date));