如果在联合中未找到任何行,请选择一些默认值

时间:2018-08-02 13:30:41

标签: sql-server-2008

我正在尝试执行类似的操作,其中不存在ID = 2的行

SELECT 
     coalesce( ID, 1 ) as ID 
     , coalesce( someVal, 0 ) as someVal
     FROM tablename WHERE ID = 1
UNION ALL
SELECT 
     coalesce( ID, 2 ) as ID 
     , coalesce( someVal, 0 ) as someVal
     FROM tablename WHERE ID = 2
UNION ALL
SELECT 
     coalesce( ID, 3 ) as ID 
     , coalesce( someVal, 0 ) as someVal
     FROM tablename WHERE ID = 3

我得到的是

ID   |    someVal
1    |    500.23
3    |    492.01

我想要的是

ID   |    someVal
1    |    500.23
2    |    0
3    |    492.01

如果没有对应ID的记录,如何使它返回带有一些默认值的行?

2 个答案:

答案 0 :(得分:0)

我相信您想在两个不同的选择中选择两个列

f.readlines

代码:

 SELECT ISNULL((SELECT isnull( ID, 2 ) FROM #tablename WHERE ID = 2),2) ,
 ISNULL((SELECT isnull( someval, 2 ) FROM #tablename WHERE ID = 2),0)

答案 1 :(得分:0)

您需要具有ID值的数字表,并将LEFT JOIN与原始表一起使用,如下所示。根据您的需要,数字表也可以是临时表。

DECLARE @tbl table(ID INT IDENTITY, SomeVal INT) 
INSERT INTO @tbl VALUES
(1)  
,(2)
,(3); 

DECLARE @numtbl TABLE(ID INT);
INSERT INTO @numtbl VALUES
(1)  
,(2)
,(3)
,(4) -- not present in original table
,(5); --not present in original table

SELECT (t.ID) as id, COALESCE(t1.SomeVal,0)  as someval
FROM
@numtbl AS t 
LEFT JOIN @tbl AS t1
ON t.ID = t1.ID 
WHERE t.ID = 5 -- ID is not present in original table