我有下面的sql,然后我计算应用程序代码中的一个字段(market_cap)而不是sql。我想计算它,然后根据从它计算的前7个顺序排列记录。
Proposed-ish Sql:
SELECT TOP 7 'market_cap' as [market_cap_calc] ??, [tradingcode],[last],[prvclose],[currentsharesonissue]
FROM [PricesCurrent]
ORDER BY tradingcode DESC
字段market_cap的Asp代码:
If Not IsNull(rs("last")) Then
marketcap = 0
If Not IsNull(rs("currentsharesonissue")) And Cdbl(rs("last")) <> 0 Then marketcap = (CDbl(rs("last")) * CDbl(rs("currentsharesonissue")))/1000000.0
End If
If marketcap = 0 And Not IsNull(rs("prvclose")) Then
If Not IsNull(rs("currentsharesonissue")) And CDbl(rs("prvclose")) > 0 Then marketcap = (CDbl(rs("prvclose")) * CDbl(rs("currentsharesonissue")))/1000000.0
End If
所以基本上它需要检查last或prvclose是否为空,然后乘以currentsharesonissue得到marketcap,然后根据该marketcap数字获得前7行,我该怎么做呢?先制作临时表?
答案 0 :(得分:1)
您可以使用coalesce
和cte
WITH CTE AS(
SELECT
coalesce([last],[prvclose],0) * currentsharesonissue as CalculatedColumn
FROM [PricesCurrent])
select top 7 * from cte order by CalculatedColumn desc
COALESCE()
将获取第一个NOT NULL
值并将其乘以currentsharesonissue
列。然后,我们按照您所说的TOP7
顺序(假设)获得DESCENDING
。