2017-10-04 84 views
3

我有一个查询,像这样:SQL - 默认选择,如果空

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

这会从我的价格订购Inventory表中返回的ID,名称,价格,布局规划。通过这个查询,我得到3行返回,最后一行有一个平面图值,其他两个是空的。是否有可能获得非空的平面布局来替换空的布局图列?我不想将这些分组,因为我需要返回3行。

+1

哇,你给了很多建议bounties..one不过的,对预期的结果和当前结果SQL的问题,再加上张贴你已经尝试将帮助 – TheGameiswar

回答

2

找出最大平面布置图的。使用isnull函数,每当它为空时,将floorplan替换为最大值。

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

这个工作好得多 – user979331

+0

isnull在这里不需要,如果有超过1行的值不为NULL,这个逻辑将失败。然后,它会带回额外的行。只需使用max()并删除条件检查就更明智了。 – scsimon

+0

@scsimon我只是想了解你的评论..你的意思是它会有一个错误'子查询返回多行'?但子查询中有一个最大值函数,所以我们不会在任何时候获得一行以上的数据。 – Valli

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

这应该适用于你的3行,但如果将有更多的记录,我会放入TOP 1。你需要指定你想要的平面布置图,看是否超过1是不是空

+0

完美的!这工作!谢谢! – user979331

+0

使用没有ORDER BY的TOP意味着你不关心*返回哪些*行。结果可能因每个查询@ user979331而异。一些事情**非常**谨慎。 – scsimon

+0

这是错误的。没有订单,并不意味着你每次都得到不同的结果。如果没有添加数据,每次都会得到相同的结果。它默认由群集密钥排序,在这种情况下应该是id – Bave

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

这不需要两次访问表 – TheGameiswar

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

+0

我认为这与其他答案和用户只提到三行相同,所以我认为不需要关联 – TheGameiswar

+0

在sqlfiddle粘贴第一个查询和干燥器有平面布置图'Y'。那是正确的行为? –