日期:2014-05-18 浏览次数:20704 次
;with cte as ( select 1 as row union select 2 union select 3 union select 4 union select 5 ) select a.row,isnull(b.score,0) score from cte a left join tb b on a.row = b.id
------解决方案--------------------
select b.id,isnull(a.score,0) as score
from
(select 1 as id union select 2 union select 3 union select 4 union select 5) b
left join a on a.id=b.id
------解决方案--------------------
create table tb(id int,score int) insert into tb select 1,80 insert into tb select 2,90 insert into tb select 3,100 go select a.number,isnull(b.score ,0)score from master..spt_values a left join tb b on a.number=b.id where type='p' and a.number in(1,2,3,4,5) /* number score ----------- ----------- 1 80 2 90 3 100 4 0 5 0 (5 行受影响) */ go drop table tb
------解决方案--------------------
IF NOT OBJECT_ID('tb') IS NULL DROP TABLE tb Go CREATE TABLE tb ( [id] INT, [score] INT ) INSERT tb SELECT 1 , 80 UNION ALL SELECT 2 , 90 UNION ALL SELECT 3 , 100 Go SELECT a.number , ISNULL(b.[score], 0) [score] FROM master.dbo.spt_values a LEFT JOIN dbo.TB b ON a.number = b.ID WHERE type = 'P' AND number IN ( 1, 2, 3, 4, 5 ) /* number score ----------- ----------- 1 80 2 90 3 100 4 0 5 0 */
------解决方案--------------------
select * from a right join (select 1 as id union select 2 union select 3 union select 4 union select 5) b on a.id =b.id
------解决方案--------------------
if object_id('tb','U') is not null drop table tb go create table tb ( id int, score int ) go insert into tb select 1,80 union all select 2,90 union all select 3,100 go select number,isnull(score,0) from master..spt_values a left join tb b on a.number=b.id where type='p' and number between 1 and 5 go /* number ----------- ----------- 1 80 2 90 3 100 4 0 5 0 (5 行受影响) */