我有以下表结构:
表c_alert:
|dynamic|symbol|price_usd|
--------------------------
|5 |BTC |13000 |
表c_current:
|symbol|price_usd|
------------------
|BTC |13600 |
我有这个问题:
SELECT dbo.c_alert.symbol, dbo.c_alert.price_usd AS alert_price, dbo.c_current.price_usd AS current_price, (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd AS pct_diff, dbo.c_alert.dynamic AS pct
FROM dbo.c_alert INNER JOIN
dbo.c_current
ON dbo.c_alert.symbol = dbo.c_current.symbol AND
dbo.c_alert.dynamic > (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd
返回此内容:
|symbol|alert_price|current_price|pct_diff|dynamic|
-----------------------------------------------
|BTC |13000 |13613.3000 |4.7 |5 |
财务查询不是很强...基本上我想知道alert_price和current_price之间的价格差异何时等于或大于动态列中的值作为布尔值。因此差异等于或大于5%的地方显示为True,否则为False。对于c_alert表中的每一行,该动态值(整数)可能会发生变化。希望有人可以提供查询解决方案。
答案 0 :(得分:1)
因为查询中的多个位置需要相同的百分比差异,所以我可能首先使用CTE来计算这个术语。然后,在CTE上进行简单的查询以获得所需的输出。
WITH cte AS (
SELECT
t2.symbol,
t2.dynamic,
t2.price_usd AS alert_price,
t1.price_usd AS current_price,
100.0*(t1.price_usd - COALESCE(t2.price_usd, 0.0)) / t2.price_usd AS pct_diff
FROM dbo.c_current t1
LEFT JOIN dbo.c_alert t2
ON t1.symbol = t2.symbol
)
SELECT
symbol,
alert_price,
current_price,
pct_diff,
dynamic,
CASE WHEN pct_diff > dynamic THEN 'TRUE' ELSE 'FALSE' END AS result
FROM cte;
修改强>
逻辑似乎在下面的演示中起作用。如果您仍有问题,请编辑演示并将链接粘贴到某处作为注释。
答案 1 :(得分:0)
使用表别名,以便查询更容易编写和读取。然后只需使用case
:
SELECT a.symbol, a.price_usd AS alert_price,
c.price_usd AS current_price,
(c.price_usd - a.price_usd) * 100.0 / a.price_usd AS pct_diff,
a.dynamic AS pct,
(case when (a.price_usd - c.price_used) > a.dynamic
then 'true' else 'false'
end) as flag
FROM dbo.c_alert a INNER JOIN
dbo.c_current c
ON a.symbol = c.symbol AND
a.dynamic > (c.price_usd - a.price_usd) * 100.0 / a.price_usd;
SQL Server没有布尔类型,所以这使用了一个字符串。您可以改为使用0
和1
。