SQL编号大于选择结果

时间:2018-02-14 11:45:39

标签: sql sql-server tsql

我正在努力想办法用T-SQL做到这一点。

我有一张表,每隔5秒就会填充三种货币(英镑,欧元和美元)的价格

我创建了一个触发器(插入后),它选择为给定货币输入的最后5个记录:

SELECT TOP 5 Price from dbo.prices where coin='GBP' ORDER BY Date Desc

我想确定上次插入的货币价格是否大于上面选择的5,我该怎么做?

由于

3 个答案:

答案 0 :(得分:1)

我猜:同一货币一次不能有两个条目。每个时间每个货币只有一个插入(5秒)。所以这应该符合你的要求:

declare @prices  table ([Date] int IDENTITY(1,1) primary key, Price float, coin varchar(3));  
insert into @prices  (coin, Price) values 
('GBP', 3.20),('EUR', 3.14),('USD', 3.14),
('GBP', 3.17),('EUR', 3.16),('USD', 3.11),
('GBP', 3.14),('EUR', 3.13),('USD', 3.16),
('GBP', 3.15),('EUR', 3.12),('USD', 3.17),
('GBP', 3.16),('EUR', 3.17),('USD', 3.11),
('GBP', 3.15),('EUR', 3.14),('USD', 3.12),
('GBP', 3.19),('EUR', 3.14),('USD', 3.16)

select
    case
        when NEW.Price > PREV.Price Then 'yes'
        else 'No'
    end as CURR_JUMP_UP
from
    (
        select top 1 COALESCE(Price,0) Price, [Date]
        from @prices where coin='GBP' order by [Date] desc
    ) NEW
    cross apply
    (
        select MAX(Price) Price from
        (
            select top 5 Price
            from @prices
            where coin='GBP' and [Date]<NEW.[Date]
            order by [Date] desc
        ) t
    ) PREV

答案 1 :(得分:0)

尝试此查询:

DECLARE @AmountLastFiveEntry DECIMAL= (SELECT TOP 5 SUM(Price) FROM dbo.prices WHERE 
    ID NOT IN (SELECT TOP 1 ID 
    FROM dbo.prices where coin='GBP' ORDER BY Date Desc) where coin='GBP' ORDER BY Date Desc)
     IF  @AmountLastFiveEntry<(SELECT TOP 1 Price 
    FROM dbo.prices where coin='GBP' ORDER BY Date Desc)
    BEGIN
    SELECT @AmountLastFiveEntry --To do task
    END

答案 2 :(得分:0)

触发器部分令人困惑

如果最新价格高于(或等于)前5的最大价格,则会报告。

declare @currency table (iden int IDENTITY(1,1) primary key, exchange smallint,  coin tinyint);  
insert into @currency (coin, exchange) values 
       (1, 1)
     , (1, 2)
     , (1, 3)
     , (1, 4)
     , (1, 5)
     , (1, 6)
     , (2, 1)
     , (2, 2)
     , (2, 3)
     , (2, 4)
     , (2, 5)
     , (2, 3);

select cccc.coin, cccc.exchange 
     , case when cccc.rn = cccc.rne then 'yes'
            else 'no'
       end  as 'high'
from ( select ccc.iden, ccc.coin, ccc.exchange, ccc.rn 
            , ROW_NUMBER() over (partition by ccc.coin order by ccc.exchange desc, ccc.rn) rne 
       from ( select cc.iden, cc.coin, cc.exchange, cc.rn  
              from ( select c.iden, c.coin, c.exchange 
                          , ROW_NUMBER() over (partition by coin order by iden desc) as rn
                     from @currency c
                   ) cc 
              where cc.rn <= 6 
            ) ccc
     ) cccc
where cccc.rn = 1
order by cccc.coin
相关问题