sales
-id
-user_id
-amount
-datetime
sales表每天为每个user_id获取一条新记录。
我希望有一个选择查询,该查询可以向我返回当天的所有行,前提是“金额”与前几天不同。
更新
5 123 700 2017/01/05
4 123 500 2017/01/04
3 123 1500 2017/01/03
2 123 1500 2017/01/02
1 123 500 2017/01/01
因此,如果您在5日搜索记录,则会获得1行,因为它与前几天有所不同。
5 123 700 2017/01/05
但是,如果您在第3次运行查询,由于金额$ 1500与第2次相同,因此您将获得0个结果。
希望这可以清除它。
答案 0 :(得分:2)
您可以尝试为此使用Lead()和Lag()SQL Analytic函数
SELECT *
from (SELECT *, LAG(AMOUNT) over (partition by user_id order by datetime) as Yesterday_AMOUNT
from SALES s
) x
where cast(s.datetime as date) = cast(getdaate() as date) and
x.AMOUNT <> s.Yesterday_AMOUNT;
答案 1 :(得分:0)
您似乎想要:
select *
from (select *, lag(amount) over (partition by user_id order by datetime) as prev_amt
from sales s
) s
where cast(s.datetime as date) = cast(getdaate() as date) and
s.amount <> s.prev_amt;
答案 2 :(得分:0)
如果每天仅提交一个金额,查询将很有帮助。 首先需要找到以前的金额。您可以使用分析函数lag()over()。
select *
from (
select *
, lag(amount) over (partition by id order by datetime) as prev_amount
from sales
) as t1
where prev_amount <> amount
and trunc(datetime) = 'today'
答案 3 :(得分:-1)
此查询对您有帮助
SELECT r1.Code, r1.Date, r1.Rate
FROM RateTable r1
WHERE r1.Rate <> (SELECT TOP 1 Rate
FROM RateTable
WHERE Date < r1.Date
ORDER BY Date DESC)