繁体   English   中英

SQL编号大于选择结果

[英]SQL number greater than select results

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

我有一个表格,该表格每5秒填充三种货币(GBP,EUR和USD)的价格

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

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

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

谢谢

我猜想:一次不能有两个输入相同货币的条目。 每一段时间(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

试试这个查询:

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

触发部分令人困惑

这将报告最新价格是否高于(或等于)先前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

暂无
暂无

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

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