我有一个问题。所以我在数组中有这些数据:
id idm amount date
1 5 10 2017-08-23 12:12:12
2 5 20 2017-08-23 12:14:16
3 6 13 2017-08-23 18:00:00
4 5 25 2017-08-24 19:00:00
5 5 160 2017-08-24 19:30:00
因此,我们的想法是从日期2017-08-23
获取金额总和,并与日期2017-08-24
进行比较。如果用户的这两个值之间的差异大于20,例如在这种情况下,我找到了一个用户。
我的建议是制作2个sql:
select sum(amount) as previous_amount, idm
FROM table
WHERE date >= '2017-08-23 00:00:00' AND date <= '2017-08-23 23:59:59'
GROUP By idm
select sum(amount) as actual_amount, idm
FROM table
WHERE date >= '2017-08-24 00:00:00' AND date <= '2017-08-24 23:59:59'
GROUP By idm
并在php中进行处理,但也许在sql中存在一种方法。你能帮我吗 ? Thx提前和抱歉我的英语。
答案 0 :(得分:1)
未经测试,但这可能有用..
domain.com/new/*
如果你能提供一个可以帮助我们帮助你的小提琴。
答案 1 :(得分:1)
如果我正确理解,这就是你想要的:
select
idm,
sum(case when date >= '2017-08-23 00:00:00' AND date <= '2017-08-23 23:59:59' then amount end) -
sum(case when date >= '2017-08-24 00:00:00' AND date <= '2017-08-24 23:59:59' then amount end) as diff
from your_table
group by idm
having diff not between -20 and 20
答案 2 :(得分:1)
我的方法是计算每idm
和day
的差异(我会告诉您如何),并在代码中完成其余工作。因此,在查看第一部分时,我使用datetime
操作函数从日期时间值中删除时间元素,该日期时间值仅将日期保留为字符串。现在我们可以分组:
select sum(amount) as previous_amount, idm, DATE_FORMAT(`date`, '%Y-%m-%d') as day
FROM test
GROUP By idm, day
order by idm, day
这会给你类似的东西:
previous_amount idm day
30 5 2017-08-23
185 5 2017-08-24
13 6 2017-08-23
此时我会继续使用代码。但是,如果要在数据库中执行此操作,则需要将上述结果表连接到自身。这模拟了LAG / LEAD行为(MySQL中没有的两条Oracle指令)。所以查询是:
select
diff1.idm,
previous_amount,
actual_amount,
diff2.actual_amount-diff1.previous_amount as difference,
diff1.day as from_day,
diff2.day as to_day
from (
select sum(amount) as previous_amount, idm, DATE_FORMAT(`date`, '%Y-%m-%d') as day
FROM test
GROUP By idm, day
order by idm, day
) as diff1
left join (
select sum(amount) as actual_amount, idm, DATE_FORMAT(`date`, '%Y-%m-%d') as day
FROM test
GROUP By idm, day
order by idm, day
) as diff2 on diff1.idm=diff2.idm
where DATE(diff2.day) > DATE(diff1.day)
and diff2.actual_amount-diff1.previous_amount > 20;
以上结果如下:
idm previous_amount actual_amount difference from_day to_day
5 30 185 155 2017-08-23 2017-08-24
请注意,上述查询保证day2&gt; day1但不强制只有一天的差异。但是,我认为可以相当容易地扩展它。
更新#1
如果您想保证单日差异,请将where
条件替换为TIMESTAMPDIFF(DAY, diff1.day, diff2.day) = 1
fiddle
答案 3 :(得分:0)
尝试一下,应该比@Shuddh解决方案更快,因为它不依赖于连接
Chunk chunk = new Chunk("Hello world",
FontFactory.getFont(FontFactory.COURIER,
20,
Font.NORMAL,
new BaseColor(255, 0, 0)));
chunk.setSkew(0, 25);
document.add(chunk);