FIRST_VALUE和LAST_VALUE的值为NULL

时间:2019-05-28 00:34:58

标签: sql-server

我想获得前2名最贵的书和最便宜的2本价格 使用FIRST_Value和LAST_Value SQL Server

空值的存在给出了不正确的最低价格值,我希望最低价格忽略空值

source1 = df
p1.circle('A', 'B', source=source1)

source2 = df
p2 = figure()
p2.circle('C', 'D', source=source2)

sourceN = df
p2 = figure()
p2.circle('X', 'Y', source=sourceN)

获取此输出

Select top 2 FIRST_VALUE(price) Over(Order by price) as MinPrice,
FIRST_VALUE(title) Over (order by price) as MinName,
LAST_VALUE(price) Over (order by price desc) as MaxPrice,
LAST_VALUE(title) over (Order by price desc) as MaxName
from titles; 

我期望的结果应该是

MINPrice    MINName                        Maxprice           MaxName
NULL       The Psychology of Computer        $22.95      But is it Friendly?
NULL       The Psychology of Computer        $21.59      Computer Phobic and 

那我该如何从最低价格中消除空值

2 个答案:

答案 0 :(得分:0)

SELECT min(value) FROM table WHERE value IS NOT NULL.

应该是这样的。

答案 1 :(得分:0)

您可以尝试

;WITH ctemin AS 
(
   SELECT TOP 2 price AS minprice, title AS mintitle FROM titles WHERE price IS NOT NULL ORDER BY price 
),
ctemax AS 
(
   SELECT TOP 2 price AS maxprice, title AS maxtitle FROM titles WHERE price IS NOT NULL ORDER BY price DESC
)

SELECT ctemin.minprice,ctemin.mintitle,ctemax.maxprice,ctemax.maxtitle FROM ctemax
INNER JOIN ctemin ON 1=1