SQL - SELECT默认为null

时间:2017-10-04 17:33:19

标签: sql sql-server

我有这样的查询:

SELECT id, name, price, floorplan 
FROM Inventory 
ORDER BY price

这将返回按价格订购的Inventory表中的ID,名称,价格,平面图。使用此查询,我返回3行,最后一行有一个floorplan值,另外两行是null。是否有可能获得非null布局规划来替换空布局规划列?我不想将这些分组,因为我需要返回3行。

4 个答案:

答案 0 :(得分:4)

您可以使用像max() over()这样的窗口函数聚合:

select 
    id
  , name
  , price
  , max(floorplan) over () as floorplan
from Inventory 
order by price

rextester演示:http://rextester.com/GDWH85581

使用此测试设置:

create table inventory (id int, name varchar(32), price decimal(9,2), floorplan int)
insert into inventory values 
 (1,'one',1.01,null)
,(2,'two',2.02,null)
,(3,'three',3.03,1024)

返回:

+----+-------+-------+-----------+
| id | name  | price | floorplan |
+----+-------+-------+-----------+
|  1 | one   | 1.01  |      1024 |
|  2 | two   | 2.02  |      1024 |
|  3 | three | 3.03  |      1024 |
+----+-------+-------+-----------+

答案 1 :(得分:2)

SELECT id, name, price, 
       (SELECT TOP 1 floorplan FROM Inventory WHERE floorplan IS NOT NULL) as [floorplan]
  FROM Inventory

这应该适用于你的3行,但如果会有更多记录,我会输入TOP 1。如果多于1不为空,则需要指定要查看的平面布局

答案 2 :(得分:2)

找出最大平面图。使用isnull函数,将floorplan替换为其最大值,只要它为null。

  SELECT id, 
         name, 
         price, 
         isnull(floorplan, (select max(floorplan) from Inventory) )
    FROM Inventory 
ORDER BY price

答案 3 :(得分:1)

考虑这个例子。我认为子查询应该是相关的。如果没有烘干机进行布局规划,但数据中没有一个。感谢

    CREATE TABLE Inventory 
    (id int 
    ,name varchar(30)
    ,price money
    ,floorplan char(1)
    )

    insert inventory 
    SELECT 1, 'Washer', 300, NULL
    insert inventory 
    SELECT 1, 'Washer', 330, NULL
    insert inventory 
    SELECT 1, 'Washer', 340, 'Y'
    insert inventory 
    SELECT 2, 'Dryer', 275,  NULL

    SELECT id, name, price, 
        (SELECT TOP 1 floorplan FROM Inventory AS Y WHERE floorplan IS NOT NULL
        AND Y.id = I.id) as [floorplan]
    FROM Inventory AS I

http://sqlfiddle.com/#!6/ca73e6/3