首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问一个记录为空的有关问题

2012-02-03 
请教一个记录为空的问题比如SQL语句select sum(score),userid from tab where userid in(1,2,3,4,5,6) gro

请教一个记录为空的问题
比如SQL语句
select sum(score),userid from tab where userid in(1,2,3,4,5,6) group by userid
order by sum(score) desc

现在只有2和6用户有积分记录,其他几位没有,所以查出来的结果就类似
200 2
90 6

我想其他没有积分记录的显示0,应该怎么写呢?
200 2
90 6
0 1
0 3
0 4
0 5

谢谢!

[解决办法]

SQL code
select a.userid,       score=(select sum(score) from tab where userid=a.userid) from (select 1 as userid union select 2 union select 3 union select 4 union       select 5 union select 6) aorder by 2 desc
[解决办法]
SQL code
SELECT  ISNULL(b.score, 0) score ,        a.number useridFROM    master..spt_values a        LEFT JOIN ( SELECT  SUM(score) score ,                            userid                    FROM    tab                    WHERE   userid IN ( 1, 2, 3, 4, 5, 6 )                    GROUP BY userid                  ) b ON a.number = b.useridWHERE   a.type = 'P'        AND a.number IN ( 1, 2, 3, 4, 5, 6 )
[解决办法]
SQL code
select isnull(n.score,0) score , m.userid from(select 1 userid union select 2 userid union select 3 userid union select 4 userid union select 5 userid union select 6 userid ) mleft join(select sum(score) score,userid from tab where userid in(1,2,3,4,5,6) group by userid) non m.userid = n.useridorder by score desc , m.userid 

热点排行