[英]SQL Return results where number of different related entities is greater than 1
[英]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.