sql计算列值然后按顺序排序

时间:2017-05-22 14:11:51

标签: sql sql-server asp-classic

我有下面的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行,我该怎么做呢?先制作临时表?

1 个答案:

答案 0 :(得分:1)

您可以使用coalescecte

执行此操作
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