SQL Query需要显示空白记录

时间:2011-04-06 07:55:44

标签: sql-server

我有一个查询,我从数据库中选择50个ID并按ID分组。

唯一的问题是数据库中只存在34个,因此它只显示34个结果。

我想要的结果是显示50个不存在的结果。

这可能吗?

由于

我的查询

SELECT no, count(no) as visits FROM DB 
WHERE (no = '1' or no = '2'  or no = '3' or no = '4' or no = '5')
GROUP BY no

这个例子只给我3条记录,即使我选择了5条记录

2 个答案:

答案 0 :(得分:2)


with noTable
as 
( select 1 as no
union
  select 2
union 
  select 3
union 
  select 4
union 
  select 5
)

select noTable.no,count(*) 
  from noTable inner join DB 
  on noTable.no = DB.no group by noTable.no
union
select noTable.no,0
  from noTable left join DB
  on noTable.no = DB.no
  where DB.no is null;

如果有50个身份......可能不优雅。

答案 1 :(得分:1)

您可以使用原始表格的WITHLEFT JOIN添加计数表和计数表。

;with q (no) AS (
  SELECT 1
  UNION ALL 
  SELECT no + 1
  FROM   q
  WHERE  no < 50
)
SELECT  q.no
        , CASE WHEN db.no IS NOT NULL 
               THEN COUNT(q.no)
               ELSE 0 
          END AS Visits
FROM    q
        LEFT JOIN db ON db.no = q.no
GROUP BY
        no