select evt_block_time, evt_tx_hash, "from", "to", cast(value as double) as amount,cast(value as decimal(38, 0)) as amount2from erc20_ethereum.evt_Transferwhere evt_block_time >=date('2022-12-18') and evt_block_time <date('2022-12-19')and evt_tx_hash in ( 0x2a5ca5ff26e33bec43c7a0609670b7d7db6f7d74a14d163baf6de525a166ab10, 0xb66447ec3fe29f709c43783621cbe4d878cda4856643d1dd162ce875651430fc )
select1 as valunion allselectcast('2' as int) as val
当我们遇到类似"Error: Line 47:1: column 1 in UNION query has incompatible types: integer, varchar(1) at line 47, position 1."这种错误时,就需要处理相应字段的类型兼容问题。
转换为double类型解决数值范围溢出错误
Dune SQL 支持整数类型 int 和 bigint,但是由于EVM等区块链不支持小数导致数值经常很大,比如当我们计算gas 费的时候,就可能遇到数值溢出的错误。下面的SQL,为了故意导致错误,我们将计算的gas fee乘以1000倍了:
selecthash, gas_price * gas_used *1000 as gas_feefrom ethereum.transactions where block_time >=date('2022-12-18') and block_time <date('2022-12-19')order by gas_used desclimit10
selecthash, cast(gas_price as double) * gas_used *1000 as gas_feefrom ethereum.transactions where block_time >=date('2022-12-18') and block_time <date('2022-12-19')order by gas_used desclimit10
selecthash, gas_used, gas_limit, gas_used / gas_limit as gas_used_percentagefrom ethereum.transactions where block_time >=date('2022-12-18') and block_time <date('2022-12-19')limit10
selecthash, gas_used, gas_limit,cast(gas_used as double) / gas_limit as gas_used_percentagefrom ethereum.transactions where block_time >=date('2022-12-18') and block_time <date('2022-12-19')limit10
select num from unnest(sequence(1, 10)) as t(num)-- select num from unnest(sequence(1, 10, 2)) as t(num) -- step 2
日期序列
Duen SQL使用unnest()搭配sequence()来生成日期序列值并转换为多行记录。
Dune SQL生成日期序列的语法:
select block_date from unnest(sequence(date('2022-01-01'), date('2022-01-31'))) as s(block_date)-- select block_date from unnest(sequence(date('2022-01-01'), date('2022-01-31'), interval '7' day)) as s(block_date)
Dune SQL 还有一个潜在的高级功能,就是允许针对一个已保存的查询进行查询(Query of Query)。这个功能有很多的想象空间,可简化查询逻辑,优化缓存使用等。比如,你可以将一个复杂的查询的基础部分保存为一个query,然后基于此query来进一步的汇总统计。这个功能貌似有时还不太稳定。不过大家可以试试。
-- original query: https://dune.com/queries/1752041select*from query_1752041where user_status ='Retained'
-- original query: https://dune.com/queries/1752041select*from query_1752041where user_status ='Churned'