【问题标题】:FIRST_VALUE and LAST_VALUE with NULL values具有 NULL 值的 FIRST_VALUE 和 LAST_VALUE
【发布时间】:2019-05-28 09:48:35
【问题描述】:

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

Null 的存在给出了不正确的 Min 价格值,我希望 Min 价格忽略 Null

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 

我期望的结果应该在哪里

Minprice     MinName                        Maxprice          Maxname           
$2.99        The Gourmet Microwave           $22.95       But is it Friendly?
$2.99        You can Combat stress          $21.59       Computer Phobic and 

那么我如何从 Min price 中消除 NULLs

【问题讨论】:

标签: sql-server


【解决方案1】:

你可以试试

;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

【讨论】:

    【解决方案2】:
    SELECT min(value) FROM table WHERE value IS NOT NULL.
    

    应该是这样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多